javascript – 与MutationObserver等效的DOMNodeInserted DOMNodeRemoved?

我目前有代码:

$('.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,
    });

最佳答案 .addedNodes返回NodeList而不是Array,它没有.forEach()方法.尝试使用Array.prototype.slice()将.addedNodes转换为具有方法.forEach()的Array

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>
点赞