表更改内容时调用Javascript函数 [英] Call a Javascript function when a table change content
问题描述
我有一个Javascript代码,该代码将数字格式化为货币.所有内容都在桌子上.目前,每个<tr>
中都有一个类money
,并且在单元格更改时调用该函数.仅供参考,表格中的所有单元格都同时更改.
I have a Javascript code which format a number as a currency. All the content is on a table. At the moment, I have a class money
in every <tr>
and I call the function when the cell change. FYI, all the cells change at the same time in the table.
var spans = document.getElementsByClassName("money");
for (var i = 0; i < spans.length; i++) {
var newText = spans[i].innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
spans[i].innerHTML = newText;
}
除了在每个单元格上具有相同的类并在所有单元格上捕获事件之外,还有什么方法可以在表上执行并获得相同的结果吗?例如,
Is there any way instead of have the same class on every cell and catch an event on all of them, to do it on table and have the same result? For example,
$("#mytable").on('change', function() {
// put my function here and apply to every cell
});
更新:我添加了DOMSubtreeModified
并尝试遍历表中的每个单元格.但是,即使我在控制台上没有任何错误,它似乎也不起作用.
Update: I added the DOMSubtreeModified
and tried to iterate through every cell in the table. However, even if I don't have any error on the console, it doesn't seem to work.
<script type="text/javascript">
$("#resultstable").bind("DOMSubtreeModified", function() {
$('#resultstable tr').each(function() {
$('td').each(function (i, cell) {
cell.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
});
</script>