DOMNodeInserted DOMNodeRemoved 与 MutationObserver 的等价物?

Equivalent of DOMNodeInserted DOMNodeRemoved with MutationObserver?

我目前有代码:

$('.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 returns 一个 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>