我有以下脚本。 HTML 不是动态添加的。 99% 的情况下,确认弹出窗口将打开,如果确认,数据将被发布,但有时,复选框会在视觉上改变状态,但确认弹出窗口不会打开。我已经在 Windows 7 上运行的 Firefox 34.0.5 上看到了这一点,但尚未在其他浏览器上进行足够的测试。
什么可能导致这种情况发生,如何预防?
编辑。当我转到页面并快速单击复选框时,它总是会发生。
<input type="checkbox" checked="" id="makePublic">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
});
最佳答案
EDIT. It happens all the time when I go to the page and quickly click the checkbox.
然后您应该禁用该元素,直到您的 javascript 完成。问题是复选框在没有附加事件的情况下是可见的。在我看来,最好的选择是在附加事件之前禁止点击(通过将其设置为禁用或隐藏等)。
<input type="checkbox" checked="" id="makePublic" disabled="disabled">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
$("#makePublic").prop('disabled','');
});
关于javascript - 是什么导致 jQuery click 事件并不总是触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930397/