表更改内容时调用Javascript函数 [英] Call a Javascript function when a table change content

查看:88
本文介绍了表更改内容时调用Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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>

推荐答案

尝试使用

阅读 Dom事件-javascript文章

$(function(){
    $('button').on('click',function(){
        $('#mytable').append('<tr><td>Next '+($('#mytable tr').length+1)+'</td></tr>');
    });
    $("#mytable").bind("DOMSubtreeModified", function() {
        alert("Hurrey table changed");
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
    <tr>
        <td>Next 1</td>
    </tr>
</table>
<br/>
<button>Test</button>

这篇关于表更改内容时调用Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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