【问题标题】:Checkbox click event firing twice复选框单击事件触发两次
【发布时间】:2015-04-18 05:00:28
【问题描述】:

我在模态框内使用 jQuery DataTables。从该表中,我有一列包含复选框。第一次尝试获取选中复选框的值是可以的。但是,当我关闭模式并再次选择时,复选框单击事件会触发两次。这是我的代码:

//handle event for checkbox checking.
arresting_officers_table.on("change", ":checkbox", function() { 
  if($(this).is(':checked')){
    console.log('Adding!'); //this log fires twice when clicking only 1 checkbox
    //alert('checked! ' + $(this).attr('data-value'));
    arresting_officers_ids.push($(this).attr('data-value'));
    arresting_officers_names.push($(this).attr('data-name'));
  } else {
    //remove item
    var idx = arresting_officers_ids.indexOf($(this).attr('data-value'));
    arresting_officers_ids.splice(idx, 1);
    arresting_officers_names.splice(idx, 1);
  }
});

您的回复将不胜感激。谢谢!

【问题讨论】:

    标签: javascript jquery checkbox datatables


    【解决方案1】:

    使用下面的代码。在附加事件之前添加.off("change")

    阅读更多关于.off()

    删除事件处理程序。

    我假设您每次打开模型框时都附加更改事件。

    arresting_officers_table.off("change").on("change", ":checkbox", function() { 
      if($(this).is(':checked')){
        console.log('Adding!'); //this log fires twice when clicking only 1 checkbox
        //alert('checked! ' + $(this).attr('data-value'));
        arresting_officers_ids.push($(this).attr('data-value'));
        arresting_officers_names.push($(this).attr('data-name'));
      } else {
        //remove item
        var idx = arresting_officers_ids.indexOf($(this).attr('data-value'));
        arresting_officers_ids.splice(idx, 1);
        arresting_officers_names.splice(idx, 1);
      }
    });
    

    其他选项是每次可以使用Event Delegation时附加事件 将事件附加到动态生成的元素。你可以阅读更多关于 Event Delegation

    事件委托允许我们将单个事件侦听器附加到 父元素,它将为匹配的所有后代触发 选择器,这些后代是现在存在还是被添加到 未来。

    【讨论】:

    • @JCFrane 你可以检查什么 off()。每次打开模型框时,您的代码都会将更改事件附加到复选框。 。离开()。将删除事件并 .on() 再次分配事件。
    • 对不起,我现在才接受。再次使用 stackoverflow =) TY 的初学者。
    • :) 随时.. 很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多