用DOMSubtreeModified替代MutationObserver存在问题

4

我正在尝试检查是否向表格中添加了新的表格行(<tr>):

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

但是,如果例如同时向表中添加10行,则会在控制台上打印出100个“Row added”消息,即使其中一个失败了,它仍然会输出10次“Row added”。这让我想到它正在监听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个回答

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接