复选框点击事件触发两次

Checkbox click event firing twice

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

//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);
  }
});

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

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

阅读更多关于 .off()

Remove an event handler.

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

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);
  }
});

other option is attach event every time you can use Event Delegation to attach event to dynamic generated element . you can read more about Event Delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.