javascript - jQuery : Finding the select elements inside the table row and listening to change event

标签 javascript jquery dom

我有一个包含多个选择元素的行表。我已经为这个选择的元素指定了类。我需要根据类找到此选择元素的更改事件。

所以我用它来查找元素

jQuery("table").on('click', 'tr', function () {
        jQuery(this).children().find('.select1').on('change', function () {
              //my action
        });
        //and same way the next select element
});

现在,我得到了更改事件,但更改事件被多次触发。 最初一次,然后计数不断增加。我需要这方面的帮助,因为我已经被困了很长时间了。谢谢

答案:

我想监听选择的更改事件,并在该事件上向行添加更多元素。所以现在我使用 delegate() 来监听选择更改事件,然后获取父级 使用 jQuery(this).closest('tr');附加其他表数据。

jQuery('table').on('click','select1',function(){
    //get the parent
    jQuery(this).closest('tr');
    //Do the rest
});

谢谢

最佳答案

不需要tr点击事件,如果选择元素是静态的则直接注册点击处理程序

jQuery('table .select1').on('change', function () {
    //my action
});

如果它们是动态创建的,则使用 event delegation

jQuery('table').on('change', '.select1', function () {
    //my action
});

在您的代码中,每次单击 tr 时,都会将新的更改处理程序添加到该 tr 中的 select1 元素中,这不是您想要的,是吗? ?

关于javascript - jQuery : Finding the select elements inside the table row and listening to change event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568745/

相关文章:

javascript - 如何检索动态创建的元素的偏移量?

javascript - 使用 phantomJS 将数据从一个页面复制到另一个页面

javascript - chrome 和 safari 中的 getElementsByTagName 问题

javascript - 单击复选框时如何更改某些文本?

javascript - Node js 上的最大子对象数

jquery - JSON 格式错误而 JSON 有效?

json - jQuery 不处理来自 AJAX POST 的 JSON 响应

php - Javascript 无法在 php 中运行

javascript - React 中字符串的正则表达式

javascript - 使用 Prototype 从 innerHTML 中去除 <script> 标签