检查表的行是否正在更改 [英] Check if a table's rows are being changed

查看:73
本文介绍了检查表的行是否正在更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用MutationObserver(或此时的任何其他内容)来监听表中的更改。我的表 - > tbody - > tr 元素可以通过多种方式更改,例如:

I would like to use a MutationObserver (or anything else at this point) to listen for changes in my table. My table -> tbody -> tr elements can be changed in various ways, such as:


  1. 通过搜索过滤(切换< tr> - 要显示或隐藏的元素)

  2. 过滤复选框(再次切换它们)

  3. 删除< tr> -elements

  1. Filtering through search (which toggles an <tr>-element to show or hide)
  2. Filtering through checkboxes (again toggles them)
  3. Removes <tr>-elements

通过使用MutationObserver,我可以去检查表中的变化。当我删除一个元素时(因为childList和子树发生了变化),它可以工作,但是当元素的属性发生变化时,它不会触发。这是我的观察者:

By using a MutationObserver, I can go and check for changes in the table. It works when I remove an element (because the childList and subtree changes), but it does not trigger, when an element's attribute changes. Here's my observer:

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()功能非常简单:它更新了表 - > tbody - > tr - 元素背景。这意味着,如果我在观察者中检查属性更改,它将进入无限循环,因为:

My updateTable() function is pretty simple: It updates the table -> tbody -> tr-element backgrounds. This means, that if I check for attribute change in the observer, it will run into an endless loop, because:


哦有人藏了< 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

我将如何继续这一点?谢谢

How would I go on about this? Thanks

推荐答案

免责声明:它可能不是一个高效的解决方案。

Disclaimer: It may not be a performant solution.

但是在执行回调之前停用观察者呢?类似

But what about deactivating the observer before executing the callback ? Something like

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更改,然后再次放置观察者。

when you change #reports, it will fire the MutationObserver, you disconnect it, so you can do your DOM changes, and then you would place the observer again.

代码未经测试,请告知我这是否适用于您

Code not tested, so let me know if this works for you

这篇关于检查表的行是否正在更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆