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

时间:2018-07-23 10:31:03

标签: javascript jquery

我正在聊天,并且有聊天包装程序。在聊天包装程序中,将使用消息创建新的跨度。像这样:

<div id="chat-wrapper">
    <span>msg 1</span>
    <span>msg 2</span>
    <span>msg ...</span>    
</div>

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

最好是jquery。

2 个答案:

答案 0 :(得分:2)

使用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.');
    }
  }
};
<div id="chat-wrapper">
</div>

<button onclick='addNew()'>Add New</button>

答案 1 :(得分:1)

您可以在javascript中使用setInterval函数。参见下面的代码,您可以在此处每2秒检查一次子跨度的长度,并将其与先前计算的子级长度进行比较。

$(function(){
   var child = $("#chat-wrapper span").length;
   setInterval(function(){
       var newChild = $("#chat-wrapper span").length;
       if(child < newChild ) {
          console.log("child added");
          child = newChild;
       }
   }, 2000);
});