简体   繁体   English

什么原因导致jQuery点击事件并不总是被触发?

[英]What causes jQuery click event not always to fire?

I have the following script. 我有以下脚本。 The HTML is not dynamically added. HTML不是动态添加的。 99% of the time, the confirm popup will open and the data will be posted if confirmed, but every now and then, the checkbox visually changes state, but the confirm popup does not open. 99%的时间,确认弹出窗口将打开,如果确认,数据将被发布,但是不时地,复选框在视觉上改变状态,但确认弹出窗口不会打开。 I've witnessed this on Firefox 34.0.5 running on Windows 7, and haven't yet tested enough on other browsers. 我在Windows 7上运行的Firefox 34.0.5上见过这个,并且还没有在其他浏览器上测试过。

What might cause this to happen, and how can it be prevented? 可能导致这种情况发生的原因,以及如何防止这种情况发生?

EDIT. 编辑。 It happens all the time when I go to the page and quickly click the checkbox. 当我进入页面并快速单击复选框时,它会一直发生。

<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. 当我进入页面并快速单击复选框时,它会一直发生。

Then you should disable the element until your javascript has finished. 然后你应该禁用该元素,直到你的JavaScript完成。 The issue is that the checkbox is visible without the event being attached. 问题是该复选框在没有附加事件的情况下可见。 The best option in my opinion is to disallow the click (by setting it disabled or hiding etc) until after the event has been attached. 在我看来,最好的选择是禁止点击(通过设置禁用或隐藏等),直到事件被附加。

<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','');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM