我正在开发Chrome中的一个扩展,我想知道:当一个元素出现的时候,最好的方法是什么?使用普通的javascript,使用一个间隔来检查元素是否存在,或者jQuery有什么简单的方法可以做到这一点?
发布于 2013-05-24 10:07:37
由于性能问题,DOMNodeInserted
和其他DOM突变事件将被弃用--推荐的方法是使用MutationObserver来监视DOM。不过,它只在较新的浏览器中受支持,所以当MutationObserver
不可用时,您应该求助于DOMNodeInserted
。
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()
发布于 2012-12-05 02:04:31
我也遇到了同样的问题,所以我继续写了一个plugin。
$(selector).waitUntilExists(function);
代码:
;(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));
发布于 2015-11-19 15:10:36
我使用这种方法来等待一个元素出现,这样我就可以在那之后执行其他函数。
假设只有在ID为the_Element_ID
的元素出现或加载完成后才应该调用doTheRestOfTheStuff(parameters)
函数,我们可以使用,
var existCondition = setInterval(function() {
if ($('#the_Element_ID').length) {
console.log("Exists!");
clearInterval(existCondition);
doTheRestOfTheStuff(parameters);
}
}, 100); // check every 100ms
https://stackoverflow.com/questions/5525071
复制相似问题