复选框点击事件触发两次。

5
我在模态框中使用 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个回答

8

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

事件委托允许我们将单个事件监听器附加到父元素上,对于与选择器匹配的所有后代元素触发,无论这些后代元素现在是否存在或将来添加。


@JCFrane 你可以检查一下 off() 函数,它可以在你打开模型框时将代码附加到复选框的更改事件上。.off() 可以删除事件,而 .on() 会重新分配事件。 - Nishit Maheta
抱歉,我刚刚才接受了它。我是一个使用stackoverflow的初学者=)再次感谢。 - iamjc015
随时欢迎您的咨询,我很乐意为您提供帮助。 - Nishit Maheta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接