检查 table 的行是否被更改
Check if a table's rows are being changed
我想使用 MutationObserver(或此时的其他任何东西)来监听我的 table 中的变化。我的 table -> tbody -> tr
元素可以通过多种方式更改,例如:
- 通过搜索进行过滤(切换
<tr>
元素以显示或隐藏)
- 通过复选框过滤(再次切换它们)
- 删除
<tr>
个元素
通过使用 MutationObserver,我可以检查 table 中的变化。当我删除一个元素时它起作用(因为 childList 和子树发生变化),但当元素的属性发生变化时它不会触发。这是我的观察员:
var observer = new MutationObserver(function(mutations, observer) {
updateTable();
});
observer.observe(document.querySelector('#reports'), { childList: true, characterData: true, subtree: true });
我的HTML:
<table id="reports">
<thead>........
<tbody>
<tr><td>Stuff here 1</td></tr>
<tr><td>Stuff here 2</td></tr>
<tr><td>Stuff here 3</td></tr>
</tbody>
</table>
我的 updateTable()
功能非常简单:它更新 table -> tbody -> tr
元素背景。这意味着,如果我检查观察者的属性变化,它将 运行 进入无限循环,因为:
Oh someone hid the <tr>
element! Let me go change the background. Oh look, someone changed the background! Let me change the background. Oh look! .... Endless loop
我该如何继续呢?谢谢
免责声明:它可能不是一个高效的解决方案。
但是在执行回调之前停用观察者呢?像
var observe = function(){
var observer = new MutationObserver(function(mutations, observer) {
observer.disconnect(); // stop watching changes
updateTable(); // do your changes
observe(); // start watching for changes again
});
observer.observe(document.querySelector('#reports'), { childList: true, attributes: true, subtree: true });
}
所以第一次你会做
observe();
当你改变 #reports
时,它会触发 MutationObserver
,你断开它,这样你就可以做你的 DOM 改变,然后你会再次放置观察者。
代码未经测试,如果这对您有用,请告诉我
我想使用 MutationObserver(或此时的其他任何东西)来监听我的 table 中的变化。我的 table -> tbody -> tr
元素可以通过多种方式更改,例如:
- 通过搜索进行过滤(切换
<tr>
元素以显示或隐藏) - 通过复选框过滤(再次切换它们)
- 删除
<tr>
个元素
通过使用 MutationObserver,我可以检查 table 中的变化。当我删除一个元素时它起作用(因为 childList 和子树发生变化),但当元素的属性发生变化时它不会触发。这是我的观察员:
var observer = new MutationObserver(function(mutations, observer) {
updateTable();
});
observer.observe(document.querySelector('#reports'), { childList: true, characterData: true, subtree: true });
我的HTML:
<table id="reports">
<thead>........
<tbody>
<tr><td>Stuff here 1</td></tr>
<tr><td>Stuff here 2</td></tr>
<tr><td>Stuff here 3</td></tr>
</tbody>
</table>
我的 updateTable()
功能非常简单:它更新 table -> tbody -> tr
元素背景。这意味着,如果我检查观察者的属性变化,它将 运行 进入无限循环,因为:
Oh someone hid the
<tr>
element! Let me go change the background. Oh look, someone changed the background! Let me change the background. Oh look! .... Endless loop
我该如何继续呢?谢谢
免责声明:它可能不是一个高效的解决方案。
但是在执行回调之前停用观察者呢?像
var observe = function(){
var observer = new MutationObserver(function(mutations, observer) {
observer.disconnect(); // stop watching changes
updateTable(); // do your changes
observe(); // start watching for changes again
});
observer.observe(document.querySelector('#reports'), { childList: true, attributes: true, subtree: true });
}
所以第一次你会做
observe();
当你改变 #reports
时,它会触发 MutationObserver
,你断开它,这样你就可以做你的 DOM 改变,然后你会再次放置观察者。
代码未经测试,如果这对您有用,请告诉我