jQuery、复选框和 .is(":checked")

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2660323/
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-08-26 13:58:46  来源:igfitidea点击:

jQuery, checkboxes and .is(":checked")

jquerycheckboxclickischecked

提问by Ben

When I bind a function to a checkbox element like:

当我将函数绑定到复选框元素时,例如:

$("#myCheckbox").click( function() {
    alert($(this).is(":checked"));
});

The checkbox changes its checked attribute beforethe event is triggered, this is the normal behavior, and gives an inverse result.

复选框在事件被触发之前改变了它的checked 属性,这是正常行为,并给出相反的结果。

However, when I do:

但是,当我这样做时:

$("#myCheckbox").click();

The checkbox changes it checked attribute afterthe event is triggered.

该复选框在事件触发更改它已检查的属性。

My question is, is there a way to trigger the click event from jQuery like a normal click would do (first scenario)?

我的问题是,有没有办法像普通点击一样从 jQuery 触发点击事件(第一种情况)?

PS: I've already tried with trigger('click');

PS:我已经尝试过trigger('click');

回答by tcurdt

$('#myCheckbox').change(function () {
    if ($(this).prop("checked")) {
        // checked
        return;
    }
    // not checked
});

Note: In older versions of jquery it was OK to use attr. Now it's suggested to use propto read the state.

注意:在旧版本的 jquery 中,可以使用attr. 现在建议使用prop读取状态。

回答by Nick Craver

There is a work-around that works in jQuery 1.3.2and 1.4.2:

有一种适用于 jQuery 1.3.21.4.2的变通方法:

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');?????????????

But I agree, this behavior seems buggy compared to the native event.

但我同意,与本机事件相比,这种行为似乎有问题。

回答by atomless

As of June 2016 (using jquery 2.1.4) none of the other suggested solutions work. Checking attr('checked')always returns undefinedand is('checked)always returns false.

截至 2016 年 6 月(使用 jquery 2.1.4),其他建议的解决方案均无效。检查attr('checked')总是返回undefined并且is('checked)总是返回false

Just use the prop method:

只需使用 prop 方法:

$("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});

回答by Sr?an Stani?

I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:

我仍然在使用 jQuery 1.7.2 时遇到这种行为。一个简单的解决方法是使用 setTimeout 推迟点击处理程序的执行,同时让浏览器发挥其魔力:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});

回答by ChillyPenguin

If you anticipate this rather unwanted behaviour, then one away around it would be to pass an extra parameter from the jQuery.trigger() to the checkbox's click handler. This extra parameter is to notify the click handler that click has been triggered programmatically, rather than by the user directly clicking on the checkbox itself. The checkbox's click handler can then invert the reported check status.

如果您预料到这种相当不受欢迎的行为,那么解决这个问题的方法是将一个额外的参数从 jQuery.trigger() 传递到复选框的单击处理程序。这个额外的参数是通知点击处理程序点击已经以编程方式触发,而不是由用户直接点击复选框本身。然后复选框的单击处理程序可以反转报告的检查状态。

So here's how I'd trigger the click event on a checkbox with the ID "myCheckBox". Note that I'm also passing an object parameter with an single member, nonUI, which is set to true:

所以这就是我如何在 ID 为“myCheckBox”的复选框上触发点击事件。请注意,我还传递了一个带有单个成员 nonUI 的对象参数,该成员设置为 true:

$("#myCheckbox").trigger('click', {nonUI : true})

And here's how I handle that in the checkbox's click event handler. The handler function checks for the presence of the nonUI object as its second parameter. (The first parameter is always the event itself.) If the parameter is present and set to true then I invert the reported .checked status. If no such parameter is passed in - which there won't be if the user simply clicked on the checkbox in the UI - then I report the actual .checked status:

这是我在复选框的单击事件处理程序中处理它的方式。处理程序函数检查非UI 对象是否存在作为其第二个参数。(第一个参数始终是事件本身。)如果该参数存在并设置为 true,那么我会反转报告的 .checked 状态。如果没有传入这样的参数——如果用户只是点击 UI 中的复选框就不会传入——那么我会报告实际的 .checked 状态:

$("#myCheckbox").click(function(e, parameters) {
   var nonUI = false;
        try {
            nonUI = parameters.nonUI;
        } catch (e) {}
        var checked = nonUI ? !this.checked : this.checked;
        alert('Checked = ' + checked);
    });

JSFiddle version at http://jsfiddle.net/BrownieBoy/h5mDZ/

JSFiddle 版本在http://jsfiddle.net/BrownieBoy/h5mDZ/

I've tested with Chrome, Firefox and IE 8.

我已经用 Chrome、Firefox 和 IE 8 进行了测试。

回答by Superman

  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});

回答by Tejas Soni

<input id="widget-wpb_widget-3-custom_date" class="mycheck" type="checkbox" value="d/M/y" name="widget-wpb_widget[3][custom_date]" unchecked="true">    

var atrib = $('.mycheck').attr("unchecked",true);
$('.mycheck').click(function(){
if ($(this).is(":checked")) 
{
$('.mycheck').attr("unchecked",false);
   alert("checkbox checked");
}
else
{
$('.mycheck').attr("unchecked",true);
 alert("checkbox unchecked");
}
});

回答by Surya R Praveen

$("#personal").click(function() {
      if ($(this).is(":checked")) {
            alert('Personal');
        /* var validator = $("#register_france").validate(); 
        validator.resetForm(); */
      }
            }
            );

JSFIDDLE

JSFIDDLE

回答by user3607804

$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});

回答by Yuri Ghensev

In addition to Nick Craver's answer, for this to work properly on IE 8you need to add a additional click handler to the checkbox:

除了 Nick Craver 的回答之外,为了使其正常工作,IE 8您需要向复选框添加一个额外的点击处理程序:

// needed for IE 8 compatibility
if ($.browser.msie)
    $("#myCheckbox").click(function() { $(this).trigger('change'); });

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');

Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8keeps focus on checkboxes and radios when they are clicked.

否则回调只会在复选框失去焦点时触发,因为IE 8在单击复选框和收音机时会保持焦点。

Haven't tested on IE 9though.

IE 9不过没试过。