前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >jQuery的attr方法处理checkbox的问题

jQuery的attr方法处理checkbox的问题

作者头像
大江小浪
发布2018-07-24 17:03:56
9090
发布2018-07-24 17:03:56
举报
文章被收录于专栏:小狼的世界小狼的世界

现象

使用了 jQuery 1.10 的版本,想实现 checkbox 的全部选中和全部取消选中,使用了 attr 的方法,如下:

代码语言:javascript
复制
$(elem).attr(“checked”) 

测试过程中发现,第一次从未选中状态变为选中,再从选中变为未选中,是可以的。但是第二次界面上就没有任何变化了,但是查看元素,发现 checked 属性实际上已经改变了。这是什么情况呢?

原因

看一下官方对这个函数的解释

.attr() Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

然后官方还特别注明了

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

文档还特别对 attr() 和 prop() 进行了对比,总体来说 jQuery 1.6 版本之后,为了保证函数在不同环境下表现的一致性,建议对于获取 DOM 元素的固有属性,使用 prop() 方法,如果需要修改个性化(自定义)的属性字段,则需要使用 attr 方法。

关于 checked 属性,还特别说了一下,我也不知道如何用汉字区分 attribute 和 property,还是摘抄下来吧。

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property

代码语言:javascript
复制
    if ( elem.checked )
    if ( $( elem ).prop( "checked" ) )
    if ( $( elem ).is( ":checked" ) )

本文为作者原创。

参考资料: 1、jQuery attr 2、jQuery prop 3、W3C Forms

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 现象
  • 原因
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档