接受的答案使用了 2011 年过时的插件,最高支持的答案使用了 Mutation 事件,这些事件现在已已弃用 https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events.
今天,一个变异观察者 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver是您应该用来检测元素何时添加到 DOM 的方法。MutationObservers 现在在所有现代浏览器(Chrome 26+、Firefox 14+、IE11、Edge、Opera 15+ 等)中得到广泛支持。
这是一个简单的示例,说明如何使用MutationObserver
侦听何时将元素添加到 DOM。
为简洁起见,我使用 jQuery 语法来构建节点并将其插入到 DOM 中。
var myElement = $("<div>hello world</div>")[0];
var observer = new MutationObserver(function(mutations) {
if (document.contains(myElement)) {
console.log("It's in the DOM!");
observer.disconnect();
}
});
observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
$("body").append(myElement); // console.log: It's in the DOM!
The observer
每当添加或删除任何节点时,事件处理程序都会触发document
。在处理程序内部,我们执行contains
检查以确定是否myElement
现在在document
.
您不需要迭代存储在的每个 MutationRecordmutations
因为你可以执行document.contains
直接检查myElement
.
要提高性能,请替换document
与将包含的特定元素myElement
在 DOM 中。