使用MutationObserver等效DOMNodeInserted DOMNodeRemoved?

时间:2016-01-28 15:22:13

标签: javascript jquery dom mutation-observers dom-node

我目前有代码:

$('.example').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
    ....
});

哪种方法效果很好,但效率不高,已经弃用了。有什么更好的方法呢?

我一直在调查MutationObserver,但这段代码确实有用吗?

错误“mutation.addedNodes不是函数”我还需要removedNodes我意识到。

var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(node) {
          if (node.className == 'example') {
              ....
          }
        });
      });
    });
    observer.observe(document, {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: false,
    });

1 个答案:

答案 0 :(得分:2)

.addedNodes会返回NodeList而不是Array,但没有.forEach()方法。尝试使用Array.prototype.slice().addedNodes投射到具有方法Array

.forEach()



var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        var nodes = Array.prototype.slice.call(mutation.addedNodes);
        nodes.forEach(function(node) {
          if (node.parentElement.className == "example") {
              alert(node.parentElement.className)
          }
        });
      });
    });
    observer.observe(document.querySelector(".example"), {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: false,
    });

var el = document.createElement("div");
el.className = "example-child";
document.querySelector(".example").appendChild(el)

<div class="example"></div>
&#13;
&#13;
&#13;