复选框单击事件两次触发

iam*_*015 4 javascript checkbox jquery 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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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

Nis*_*eta 6

使用下面的代码.加上.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);
  }
});
Run Code Online (Sandbox Code Playgroud)

其他选项是每次可以使用Event Delegation 附加事件将事件附加到动态生成的元素时附加事件.您可以阅读有关事件委派的更多信息

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