博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jQuery的attr方法处理checkbox的问题
阅读量:2239 次
发布时间:2019-05-09

本文共 1476 字,大约阅读时间需要 4 分钟。

现象

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

$(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 方法。

39469-20170906150427897-1646491621.png

关于 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

if ( elem.checked )    if ( $( elem ).prop( "checked" ) )    if ( $( elem ).is( ":checked" ) )

本文为作者原创,未经允许不得转载。如果您觉得本文对您有帮助,请随意打赏,您的支持将鼓励我继续创作。

39469-20170825142904777-1467390737.png

参考资料:

1、
2、
3、

转载于:https://www.cnblogs.com/cocowool/p/7484857.html

你可能感兴趣的文章
JSP相关知识
查看>>
JDBC的基本知识
查看>>
《Head first设计模式》学习笔记 - 适配器模式
查看>>
《Head first设计模式》学习笔记 - 单件模式
查看>>
《Head first设计模式》学习笔记 - 工厂方法模式
查看>>
《Head first设计模式》学习笔记 - 装饰者模式
查看>>
《Head first设计模式》学习笔记 - 模板方法模式
查看>>
《Head first设计模式》学习笔记 - 外观模式
查看>>
《Head first设计模式》学习笔记 - 命令模式
查看>>
《Head first设计模式》学习笔记 - 抽象工厂模式
查看>>
《Head first设计模式》学习笔记 - 观察者模式
查看>>
《Head first设计模式》学习笔记 - 策略模式
查看>>
ThreadLocal 那点事儿
查看>>
ThreadLocal 那点事儿(续集)
查看>>
阳台做成榻榻米 阳台做成书房
查看>>
深入分析java线程池的实现原理
查看>>
mybatis中"#"和"$"的区别
查看>>
Hibernate与MyBatis区别
查看>>
如何禁用Eclipse的Validating
查看>>
据说看完这21个故事的人,30岁前都成了亿万富翁。你是下一个吗?
查看>>