代码之家  ›  专栏  ›  技术社区  ›  Brainmaniac

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

  •  3
  • Brainmaniac  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我正在做一个聊天和聊天包装。在聊天包装器中,新的跨距是用消息创建的。就像这样:

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

    有没有一种方法来观察聊天包装器是否会生下新孩子?

    最好是jquery。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Ullas Hunka    6 年前

    使用突变观察者,示例如下:

    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>
        2
  •  1
  •   Bhushan Kawadkar    6 年前

    您可以在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);
    });