当新的子元素出现在 html 元素中时触发事件

Bra*_*iac 7 javascript jquery

我正在聊天并有聊天包装器。在聊天包装器内,使用消息创建新的跨度。就像这样:

<div id="chat-wrapper">
    <span>msg 1</span>
    <span>msg 2</span>
    <span>msg ...</span>    
</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法观察#chat-wrapper 是否生了新孩子?

最好是jquery..

Ull*_*nka 8

使用Mutation Observer,示例如下:

function addNew() {
  var targetNode = document.getElementById('chat-wrapper');
  targetNode.innerHTML += '<span> Message' + targetNode.querySelectorAll('span').length + '</span>';
}

window.onload = function() {

  var targetNode = document.getElementById('chat-wrapper');


  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(callback);


  observer.observe(targetNode, config);
}



// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    if (mutation.type == 'childList') {
      console.log('A child node has been added or removed.');
    } else if (mutation.type == 'attributes') {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
  }
};
Run Code Online (Sandbox Code Playgroud)
<div id="chat-wrapper">
</div>

<button onclick='addNew()'>Add New</button>
Run Code Online (Sandbox Code Playgroud)

  • 这是*迄今为止*最好的方法。 (2认同)