复选框单击事件两次触发

时间:2015-04-18 05:00:28

标签: javascript jquery checkbox datatables

我在模态中使用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);
  }
});

非常感谢您的回复。谢谢!

1 个答案:

答案 0 :(得分:5)

使用下面的代码。在附加事件之前添加.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

     

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

相关问题