Javascript 复选框单击事件触发两次
我在模态中使用jQuery数据表。从该表中,我有一列,其中包含复选框。第一次尝试获取选中复选框的值都正常。但是,当我关闭模式并再次选择时,复选框单击事件将触发两次。这是我的密码:Javascript 复选框单击事件触发两次,javascript,jquery,checkbox,datatables,Javascript,Jquery,Checkbox,Datatables,我在模态中使用jQuery数据表。从该表中,我有一列,其中包含复选框。第一次尝试获取选中复选框的值都正常。但是,当我关闭模式并再次选择时,复选框单击事件将触发两次。这是我的密码: //handle event for checkbox checking. arresting_officers_table.on("change", ":checkbox", function() { if($(this).is(':checked')){ console.log('Adding!');
//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(“更改”)
阅读更多关于
删除事件处理程序
我假设您每次打开模型箱时都会附加更改事件
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);
}
});
另一个选项是每次可以使用事件委派时附加事件
将事件附加到动态生成的元素。你可以阅读更多关于
事件委派允许我们将单个事件侦听器附加到
父元素,该元素将为匹配
选择器,无论这些子体现在存在还是添加到
未来
@JCFrane您可以检查off()中的内容。执行。每次打开模型框时,代码都会将更改事件附加到复选框。off()。将删除事件,.on()将再次分配事件。抱歉,我现在才接受它。初学者在使用stackoverflow=)TY时可以随时使用。。很高兴帮助你