jQuery、复选框和 .is(":checked") [英] jQuery, checkboxes and .is(":checked")

查看:21
本文介绍了jQuery、复选框和 .is(":checked")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将一个函数绑定到一个复选框元素时:

When I bind a function to a checkbox element like:

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

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

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

但是,当我这样做时:

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

该复选框在触发事件后更改它选中的属性.

The checkbox changes it checked attribute after the event is triggered.

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

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

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

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

推荐答案

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

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

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

这篇关于jQuery、复选框和 .is(":checked")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆