.prop('checked',false)或.removeAttr('checked')? [英] .prop('checked',false) or .removeAttr('checked')?

查看:107
本文介绍了.prop('checked',false)或.removeAttr('checked')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着prop方法的引入,现在我需要知道取消选中复选框的可接受方法.是吗?

With the introduction of the prop method, now I need to know the accepted way of unchecking a checkbox. Is it:

$('input').filter(':checkbox').removeAttr('checked');

$('input').filter(':checkbox').prop('checked',false);

推荐答案

jQuery 3

从jQuery 3开始,removeAttr不再将相应属性设置为false:

As of jQuery 3, removeAttr does not set the corresponding property to false anymore:

在jQuery 3.0之前,在checkedselectedreadonly等布尔属性上使用.removeAttr()也会将相应的命名属性设置为false.较旧版本的Internet Explorer要求使用此行为,但对于现代浏览器而言,此行为是不正确的,因为该属性表示初始值,而该属性表示当前(动态)值.

Prior to jQuery 3.0, using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.

在DOM元素上使用.removeAttr( "checked" )几乎总是一个错误.唯一有用的时间是,如果以后将DOM序列化回HTML字符串.在所有其他情况下,应改用.prop( "checked", false ).

It is almost always a mistake to use .removeAttr( "checked" ) on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases, .prop( "checked", false ) should be used instead.

更改日志

使用此版本时,仅.prop('checked',false)是正确的方法.

Hence only .prop('checked',false) is correct way when using this version.

原始答案(从2011年开始):

对于具有基础布尔属性(其中checked为1)的属性,removeAttr自动将基础属性设置为false. (请注意,这是jQuery 1.6.1中添加的向后兼容性修复程序").

For attributes which have underlying boolean properties (of which checked is one), removeAttr automatically sets the underlying property to false. (Note that this is among the backwards-compatibility "fixes" added in jQuery 1.6.1).

所以,任何一个都可以工作...但是您给出的第二个示例(使用prop)是两者中更正确的一个.如果您的目标是取消选中该复选框,那么您确实希望影响属性而不是属性,因此无需进行removeAttr操作即可.

So, either will work... but the second example you gave (using prop) is the more correct of the two. If your goal is to uncheck the checkbox, you really do want to affect the property, not the attribute, and there's no need to go through removeAttr to do that.

这篇关于.prop('checked',false)或.removeAttr('checked')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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