在单元格中文本发生变化时的jQuery事件监听器?

在jQuery中是否有任何方法可以将监听器附加到单元格,以便当单元格内的文本发生更改时(通过JavaScript而不是用户),事件会被触发?

为了扩展mway的答案 ,这里有一些代码。

var td = $('#my-table tr td:eq(1)'); var tdHtml = td.html(); setInterval(function() { if (td.html() !== tdHtml) { // it has changed tdHtml = td.html(); } }, 500); 

……以及他的第二个建议。

 function updateTd(html) { $('#my-table tr td:eq(1)').html(html); // additional code } 

您还可以将DOMSubtreeModified事件绑定到元素,但浏览器支持不是最好的。

不是本地的,没有。 你有几个选择:

1)使用setInterval()根据其先前值测试值,如果不同则执行相应操作。

2)使用常用方法更改单元格内容,这样您还可以在更改其值时执行其他逻辑,而无需多次重写。

恐怖。 可能在2010年被接受。

  const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { // NB the 1st char put or typed into a TD causes a mutation in the TD... // but chars 2 ... n cause a mutation in its child '#text' node let target = mutation.target; if( target.cellIndex === undefined ){ target = target.parentElement; } // NB don't use a "truthy" test for cellIndex here: you would miss index 0! if( target !== null && target.cellIndex !== undefined ){ // ... then the target is the TD where the content has changed. } }); }); const config = { attributes: true, childList: true, characterData : true, subtree : true }; observer.observe( htmlTable, config );