javascript 使用 jQuery 以编程方式触发“选中”复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21164945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:16:00  来源:igfitidea点击:

Trigger a programmatically 'checked' checkbox with jQuery

javascriptcheckboxjqueryeventtrigger

提问by Mikel

I want to trigger a programmatically checkedcheckbox. eg:

我想触发一个以编程方式选中的复选框。例如:

$(function(){
    //create a trigger that if a checkbox changes, eg is clicked/change show an alert
    $("#idCheckbox").on("change", function(){
        if($(this).is(':checked')){
            alert("Is checked!");
        }
    });

    //onload put it checked
    $("#idCheckbox").attr("checked", "checked");
});

The 'problem' is that if I check on load the checkbox by javascript the on() method is not triggered, and the alert is not shown.

“问题”是,如果我通过 javascript 检查加载复选框,则不会触发 on() 方法,并且不会显示警报。

The code above is an example, in fact the script which check the checkbox is not mineand I can't modify it.

上面的代码是一个例子,实际上检查复选框的脚本不是我的,我无法修改它。

I am using jQuery 1.8.0

我正在使用 jQuery 1.8.0

Any suggestion?

有什么建议吗?

Thanks in advance.

提前致谢。

回答by hunter

Rather than setting the attribute to checked you can call click()on the checkbox to trigger the the event you had bound previously

您可以调用click()复选框来触发您之前绑定的事件,而不是将属性设置为已检查



$(function(){
    var $checkbox = $("#idCheckbox");
    $checkbox.on("change", function(){
        if(this.checked){
            alert("Is checked!");
        }
    });

    $checkbox.click();
});


example:http://jsfiddle.net/hunter/wpLb2/

示例:http : //jsfiddle.net/hunter/wpLb2/

回答by RononDex

You can move your inline defined function to global scope and call it:

您可以将内联定义的函数移动到全局范围并调用它:

function checkBoxClick(){
    if($(this).is(':checked')){
        alert("Is checked!");
    }
}

$(function(){
    //create a trigger that if a checkbox changes, eg is clicked/change show an alert
    $("#idCheckbox").on("change", checkBoxClick);

    // Trigger your click function
    checkBoxClick();    

    //onload put it checked
    $("#idCheckbox").attr("checked", "checked");


});

回答by achinmay

When a checkbox is checked programmatically using javascript, onchange event does not get fired automatically. So the script that marks the checkbox as checked should call onchange event.

当使用 javascript 以编程方式选中复选框时,不会自动触发 onchange 事件。因此,将复选框标记为已选中的脚本应调用 onchange 事件。