14

我在拖动事件后向 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');
        }
    });
}

任何人都可以帮忙,非常感谢。

4

1 回答 1

18

这是一个简单的示例,说明如何使用 aMutationObserver来侦听何时将元素添加到 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!

您不需要遍历存储的每个 MutationRecord,mutations因为您可以document.contains直接在myElement.

于 2017-07-23T16:27:13.947 回答