我在拖动事件后向 DOM 添加一些元素。我需要检测这个元素以及添加这个元素的时刻。我使用 Mutation Observer 但有些问题,代码:
var targetNodes = $('.mvly');
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver (mutationHandler);
var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true };
targetNodes.each(function(){
myObserver.observe(this, obsConfig);
} );
function mutationHandler (mutationRecords) {
mutationRecords.forEach ( function (mutation) {
if (typeof mutation.addedNodes == "object") {
console.log('test');
}
});
}
任何人都可以帮忙吗,非常感谢。
最佳答案
这是一个简单的示例,说明如何使用 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!
您不需要迭代存储在 mutations
中的每个 MutationRecord,因为您可以直接对 myElement
执行 document.contains
检查。
关于javascript - 使用 Mutation Observer 检测向 DOM 添加的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20420577/