设置“已检查"对于带有 jQuery 的复选框 [英] Setting "checked" for a checkbox with jQuery
问题描述
我想做这样的事情来使用 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 版发行说明 和属性与属性部分.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.
这篇关于设置“已检查"对于带有 jQuery 的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!