如何防止jQuery中复选框单击时执行多个代码

How to prevent multiple code execution on checkbox click in jQuery?

本文关键字:执行 代码 单击 何防止 jQuery 复选框      更新时间:2023-09-26

在我的页面上,我有这样的复选框:

<input id="check0" type="checkbox">

每次用户选中或取消选中它时,我都想执行一些jQuery代码。下面是这个代码的示例:

$("input[type=checkbox]").click(function () {
    if ($(this).is(':checked')) {
        // Calculate something here
    }
    else {
        // Or calculate something here         
    }
});

问题是:如果用户真的很快多次点击复选框,有些代码会被执行多次,因为它每次都会触发点击功能,但浏览器不会那么快改变"检查"状态!

如何防止这种情况发生?

我想放一些类似的东西:

$("input[type=checkbox]").click(function () {
    if ($(this).is(':checked')) {
        // Disable checkbox
        $(this).disabled = true;
        // Calculate something here
        // Enable it back
        $(this).disabled = false;
    }
    else {
        // Or calculate something here         
    }
});

如何使我的代码按此顺序精确执行?禁用>然后执行代码>然后重新启用?

感谢

您应该在更改时使用,而不是在单击时使用。然后检查检查的道具。如果选中,则运行代码。如果要禁用,请使用attr。

试试这个。。。

$("#check0").on("change", function () {
    if($(this).prop("checked") == true){
        alert("hey now");
        $(this).attr("disabled","disabled");
    } else {
        //nothing
    }   
});

http://jsfiddle.net/Eddieflux/z3xfcmgk/