设置“已检查”使用jQuery的复选框 [英] Setting "checked" for a checkbox with jQuery
问题描述
我想使用 jQuery 来做这样的事情以勾选复选框
:
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
属性:
DOM API
If you're working with just one element, you can always just access the underlying HTMLInputElement
and modify its .checked
property:
$('.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()
包含以下任何形式
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.
更多情况下,对 checked处理的变化的一些不完整讨论$>在属性/属性。 = noreferrer>版本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屋!