简体   繁体   English

变异观察者无法检测通过innerHTML,appendChild添加的节点

[英]Mutation Observer does not detect nodes added through innerHTML, appendChild

When we try to add nested nodes in DOM using appendChild or innerHTML, the nested nodes do not come in the addedNodes of a mutation. 当我们尝试使用appendChild或innerHTML在DOM中添加嵌套节点时,嵌套节点不会出现在突变的addNodes中。

Initial HTML setUp: 初始HTML设置:

<html>
    <body>
        <div id="container">
        </div>
    </body>
</html>

Here is my Mutation Observer code: 这是我的突变观察者代码:

var observer = new MutationObserver(function(mutations) {
  for (var i = 0; i < mutations.length; i++) {
    var mutation = mutations[i];
    switch(mutation.type) {
      case 'childList':
        console.log(mutation.addedNodes);
      break;
      default:

    }
  }
});

observer.observe(document, {
    childList: true,
    subtree: true,
    attributes: true,
    characterData: true
});

If I now do appendChild with a nested img node in a div, 如果我现在在div中使用嵌套的img节点执行appendChild,

var img = document.createElement('img');
img.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
var div = document.createElement('div');
div.appendChild(img);
var container = document.getElementById("container");
container.appendChild(div);

The Mutation Observer only logs the div which is appended to the container, but does not log the img as an addedNode in mutation. Mutation Observer仅记录附加到容器的div ,但不记录img作为突变中的addNode。

Here is a working JSFiddle: https://jsfiddle.net/aedhefhn/ 这是一个工作的JSFiddle: https ://jsfiddle.net/aedhefhn/

Is there a workaround for this? 有没有解决方法?

That is the expected behavior. 那是预期的行为。 The div was all that was appended, it just happened to have some children. div是附加的所有元素,它刚好有一些孩子。 You can certainly walk through its child nodes yourself from .addedNodes though. 当然,您当然可以自己从.addedNodes遍历其子节点。 .addedNodes is just an array of nodes, so you can go through each item recursively to get all the children. .addedNodes只是一个节点数组,因此您可以递归遍历每个项目以获取所有子项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM