简体   繁体   English

使用jQuery以编程方式“勾选”复选框

[英]Trigger a programmatically 'checked' checkbox with jQuery

I want to trigger a programmatically checked checkbox. 我想触发一个以编程方式检查的复选框。 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 mine and I can't modify it. 上面的代码是一个例子,实际上检查复选框的脚本不是我的 ,我无法修改它。

I am using jQuery 1.8.0 我正在使用jQuery 1.8.0

Any suggestion? 有什么建议吗?

Thanks in advance. 提前致谢。

Rather than setting the attribute to checked you can call click() on the checkbox to trigger the the event you had bound previously 您可以调用复选框上的click()来触发先前绑定的事件,而不是将属性设置为checked


$(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/

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");


});

When a checkbox is checked programmatically using javascript, onchange event does not get fired automatically. 当使用javascript以编程方式检查复选框时,onchange事件不会自动触发。 So the script that marks the checkbox as checked should call onchange event. 因此,将复选框标记为已选中的脚本应调用onchange事件。

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

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