将DOMSubtreeModified替换为MutationObserver问题

时间:2015-09-16 15:55:57

标签: javascript jquery dom mutation-observers

我正在尝试检查新表格行<tr>是否已添加到表中,如下所示:

var myTab;e = $('#myTable tbody');
myTab.on("DOMSubtreeModified", function() {
  console.log('Row added');
}); 

但这会打印到控制台100的&#39; Row添加&#39;消息,例如,如果同时向表中添加10行,即使其中一行仍然打印出来,行已添加&#39; 10倍。这让我觉得它正在倾听myTable中绝对不是我想要的所有变化。我只是希望它执行一次,即使添加了100行(一次批量添加行)。

我通过MutationObserver找到了另一个解决方案但是无法弄清楚如何设置它以实现我的任务(一旦将行添加到myTable)执行一次更改事件

以下是该表的示例标记。

<table id="myTable">
    <thead>
    <tr>
     <th>
      <div>Date</div>
      <span>Time</span>
   </th>
    </tr>
    </thead>

    <tbody>
    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <!-- etc.. -->
  </tbody>
</table>

这是一个非常简单的版本,包括类,数据属性,id和其他元素,但是应该这样做。

1 个答案:

答案 0 :(得分:3)

var target = $("#myTable").get(0);

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    // do stuff when
    // `childList`, `subtree` of `#myTable` modified
    alert(mutation.type);        
  });    
});

// configuration of the observer:
var config = { childList: true, subtree:true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

$("#myTable tbody").append("<tr><td>abc</td></tr><tr><td>def</td></tr>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable">
    <thead>
    <tr>
     <th>
      <div>Date</div>
      <span>Time</span>
   </th>
    </tr>
    </thead>

    <tbody>
    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <!-- etc.. -->
  </tbody>
</table>