设置“选中”与jQuery的复选框? [英] Setting "checked" for a checkbox with jQuery?

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

问题描述

我想这样做,使用 jQuery 选中复选框

  $(。myCheckBox)。checked(true); 

  $(。myCheckBox)。selected(true);这是否存在?



< >解决方案

jQuery 1.6 +



使用新的 .prop() 方法:

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



jQuery 1.5.x及以下



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

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

请注意,这是在1​​.6版之前jQuery的单元测试使用的方法,并且优于使用

  $('。myCheckbox')。removeAttr('checked'); 

,因为如果最初选中此框,后者将会将调用的行为更改为 .reset()



对于更多的上下文,有关处理更改的一些不完整的讨论。 检查属性/属性在从1.5.x到1.6的转换中可以在版本1.6发行说明以及属性与属性 .jquery.com / prop /rel =nofollow noreferrer> .prop()文档



任何版本的jQuery



如果您只使用一个元素,则可以随时修改 HTMLInputElement .checked 属性:

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

使用 .prop() .attr()方法,而不是这样,它们将操作所有匹配的元素。


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

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

or

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

Does such a thing exist?

解决方案

jQuery 1.6+

Use the new .prop() method:

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

jQuery 1.5.x and below

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

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

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.

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.

Any version of jQuery

If you're working with just one element, you can always just modify the HTMLInputElement's .checked property:

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

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

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

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