设置“选中"对于带有 jQ​​uery 的复选框 [英] Setting "checked" for a checkbox with jQuery

查看:37
本文介绍了设置“选中"对于带有 jQ​​uery 的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情来使用 jQuery 勾选 checkbox:

I'd like to do something like this to tick a checkbox using jQuery:

$(".myCheckBox").checked(true);

$(".myCheckBox").selected(true);

这样的事情存在吗?

推荐答案

现代jQuery

使用.prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

如果您只使用一个元素,您可以随时访问底层 HTMLInputElement 并修改其 .checked 属性:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

使用 .prop().attr() 方法的好处是它们将对所有匹配的元素进行操作.

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

.prop()方法不可用,需要使用.attr().

The .prop() method is not available, so you need to use .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

请注意,这是 所使用的方法jQuery 1.6 版之前的单元测试 并且比使用 $('.myCheckbox').removeAttr('checked'); 更可取,因为如果最初选中该框,后者将更改对 .reset()<的调用行为/code> 在任何包含它的表单上——一个微妙但可能不受欢迎的行为变化.

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.

有关更多上下文,可以在 版本 1.6 发行说明Attributes vs. Properties 部分.prop() 文档.

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

这篇关于设置“选中"对于带有 jQ​​uery 的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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