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

发布于 2024-08-29 14:46:43 字数 386 浏览 2 评论 0 原文

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

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

复选框在触发事件之前更改其选中属性,这是正常行为,并给出相反的结果。

但是,当我这样做时:

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

触发事件之后,复选框会更改其选中属性。

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

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

When I bind a function to a checkbox element like:

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

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

However, when I do:

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

The checkbox changes it checked attribute after the 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)?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

新一帅帅 2024-09-05 14:46:43
$('#myCheckbox').change(function () {
    if ($(this).prop("checked")) {
        // checked
        return;
    }
    // not checked
});

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

$('#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 prop to read the state.

-残月青衣踏尘吟 2024-09-05 14:46:43

有一个适用于 jQuery 1.3.21.4.2

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

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

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

There is a work-around that works in jQuery 1.3.2 and 1.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.

南风几经秋 2024-09-05 14:46:43

截至 2016 年 6 月(使用 jquery 2.1.4),其他建议的解决方案都不起作用。检查 attr('checked') 始终返回 undefined,而 is('checked) 始终返回 false

只需使用 prop 方法:

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

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

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

Just use the prop method:

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

  if ($(this).prop('checked')){
    console.log('checked');
  }
});
毁我热情 2024-09-05 14:46:43

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

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

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:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});
恋你朝朝暮暮 2024-09-05 14:46:43
$("#personal").click(function() {
      if ($(this).is(":checked")) {
            alert('Personal');
        /* var validator = $("#register_france").validate(); 
        validator.resetForm(); */
      }
            }
            );

JSFIDDLE

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

JSFIDDLE

伤痕我心 2024-09-05 14:46:43

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

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

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

以下是我在复选框的单击事件处理程序中处理该参数的方法。处理程序函数检查是否存在非 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 版本位于 http://jsfiddle.net/BrownieBoy/h5mDZ/

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

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.

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:

$("#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:

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

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

池木 2024-09-05 14:46:43
<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");
}
});
<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");
}
});
路弥 2024-09-05 14:46:43
  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});
  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});
流心雨 2024-09-05 14:46:43

嗯,为了匹配第一个场景,这是我想出的东西。

http://jsbin.com/uwupa/edit

本质上,不是绑定“click”事件,您将“更改”事件与警报绑定。

然后,当您触发事件时,首先触发点击,然后触发更改。

Well, to match the first scenario, this is something I've come up with.

http://jsbin.com/uwupa/edit

Essentially, instead of binding the "click" event, you bind the "change" event with the alert.

Then, when you trigger the event, first you trigger click, then trigger change.

寻找一个思念的角度 2024-09-05 14:46:43

除了 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');

否则只有当复选框失去焦点时才会触发回调,如 IE 8 在单击复选框和单选框时将焦点保持在它们上。

尚未在 IE 9 上进行测试。

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

// 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 8 keeps focus on checkboxes and radios when they are clicked.

Haven't tested on IE 9 though.

红玫瑰 2024-09-05 14:46:43
$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

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

});
顾铮苏瑾 2024-09-05 14:46:43

最快速、最简单的方法

$('#myCheckbox').change(function(){
    alert(this.checked);
});

$el[0].checked;

$el - 是 jquery 的选择元素。

享受!

Most fastest and easy way:

$('#myCheckbox').change(function(){
    alert(this.checked);
});

$el[0].checked;

$el - is jquery element of selection.

Enjoy!

想念有你 2024-09-05 14:46:43
if ($.browser.msie) {
    $("#myCheckbox").click(function() { $(this).trigger('change'); });
}

$("#myCheckbox").change(function() {
        alert($(this).is(":checked"));
    });
if ($.browser.msie) {
    $("#myCheckbox").click(function() { $(this).trigger('change'); });
}

$("#myCheckbox").change(function() {
        alert($(this).is(":checked"));
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文