Mutations-Observer 获取添加的元素

Mutations-Observer get added element

我正在尝试使用 mutationsobserver 仅记录添加的节点。这是我到目前为止得到的。我无法通过这部分。我卡住了。我试图在它第一次启动时获取 NodeList 索引计数,并且只使用它记录新添加的节点但最终失败了。我不知道如何做到这一点。老实说,直到今天早上我才知道突变观察者。

这是我当前的脚本

const targetNode = document.getElementById('team_log_actual');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
    if (mutation.type === 'childList') {
        console.log('a node added.' + mutation.target);
        var html = mutation.target;
        var htmlstring = JSON.stringify(html);
        console.log(html)


    }
}
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

每次添加一个新的。我只想对添加的节点进行字符串化。

您可以使用 mutation.addedNodes 查看元素中添加了哪些节点。如果你只想打印所有节点的 innerHTML,你可以这样做:

console.log( Array.from( mutation.addedNodes ).map( node => node.innerHTML ).join('\r\n') );

这将首先将 addedNodes(NodeList 类型)转换为数组,然后 map 将为每个节点检索 innerHTML。然后您可以将其连接在一起并打印出更改。

下面的代码将模拟这种行为。

对于配置,您不必检查属性或子树,childList 会做您想要它做的事情

const targetNode = document.getElementById('team_log_actual');

// Options for the observer (which mutations to observe)
const config = {
  attributes: false,
  childList: true,
  subtree: false
};

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      console.log( Array.from( mutation.addedNodes ).map( node => node.innerHTML ).join('\r\n') );
    }
  }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

let counter = 0;
setInterval(function() {
  var span = document.createElement('span');
  span.innerHTML = 'I am element ' + (++counter);
  targetNode.appendChild(span);
}, 1000);
<div id="team_log_actual"></div>