首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何等待一个元素存在?

如何等待一个元素存在?
EN

Stack Overflow用户
提问于 2011-04-03 02:32:18
回答 16查看 339.3K关注 0票数 308

我正在开发Chrome中的一个扩展,我想知道:当一个元素出现的时候,最好的方法是什么?使用普通的javascript,使用一个间隔来检查元素是否存在,或者jQuery有什么简单的方法可以做到这一点?

EN

回答 16

Stack Overflow用户

回答已采纳

发布于 2013-05-24 10:07:37

由于性能问题,DOMNodeInserted和其他DOM突变事件将被弃用--推荐的方法是使用MutationObserver来监视DOM。不过,它只在较新的浏览器中受支持,所以当MutationObserver不可用时,您应该求助于DOMNodeInserted

代码语言:javascript
复制
let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (!mutation.addedNodes) return

    for (let i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      let node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()
票数 198
EN

Stack Overflow用户

发布于 2012-12-05 02:04:31

我也遇到了同样的问题,所以我继续写了一个plugin

$(selector).waitUntilExists(function);

代码:

代码语言:javascript
复制
;(function ($, window) {

var intervals = {};
var removeListener = function(selector) {

    if (intervals[selector]) {

        window.clearInterval(intervals[selector]);
        intervals[selector] = null;
    }
};
var found = 'waitUntilExists.found';

/**
 * @function
 * @property {object} jQuery plugin which runs handler function once specified
 *           element is inserted into the DOM
 * @param {function|string} handler 
 *            A function to execute at the time when the element is inserted or 
 *            string "remove" to remove the listener from the given selector
 * @param {bool} shouldRunHandlerOnce 
 *            Optional: if true, handler is unbound after its first invocation
 * @example jQuery(selector).waitUntilExists(function);
 */

$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {

    var selector = this.selector;
    var $this = $(selector);
    var $elements = $this.not(function() { return $(this).data(found); });

    if (handler === 'remove') {

        // Hijack and remove interval immediately if the code requests
        removeListener(selector);
    }
    else {

        // Run the handler on all found elements and mark as found
        $elements.each(handler).data(found, true);

        if (shouldRunHandlerOnce && $this.length) {

            // Element was found, implying the handler already ran for all 
            // matched elements
            removeListener(selector);
        }
        else if (!isChild) {

            // If this is a recurring search or if the target has not yet been 
            // found, create an interval to continue searching for the target
            intervals[selector] = window.setInterval(function () {

                $this.waitUntilExists(handler, shouldRunHandlerOnce, true);
            }, 500);
        }
    }

    return $this;
};

}(jQuery, window));
票数 119
EN

Stack Overflow用户

发布于 2015-11-19 15:10:36

我使用这种方法来等待一个元素出现,这样我就可以在那之后执行其他函数。

假设只有在ID为the_Element_ID的元素出现或加载完成后才应该调用doTheRestOfTheStuff(parameters)函数,我们可以使用,

代码语言:javascript
复制
var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms
票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5525071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档