当前栏目
jQuery的attr方法处理checkbox的问题
现象
使用了 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 方法。
关于 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" ) )
本文为作者原创,未经允许不得转载。如果您觉得本文对您有帮助,请随意打赏,您的支持将鼓励我继续创作。
参考资料:
1、jQuery attr
2、jQuery prop
3、W3C Forms
相关文章
- vue2和vue3的区别有哪些?
- 开发中遇到的问题集合
- Spring Boot发送GET/POST请求——RestTemplate的基本使用
- web安全基础-文件上传(含部分upload-labs靶场通关)
- 小米MIUI系统组件监听用户隐私
- springboot实战——总结
- 优秀前端都应该具备的开发好习惯,坚持了效率翻倍
- OpenYurt v1.2 新版本深度解读(一): 聚焦边云网络优化
- 每个前端程序员都应该知道的10个Chrome扩展
- springboot整合activiti实现流程审批(支持单体、微服务融合)
- VS Code保存后自动格式化Vue代码
- 后端跨域问题导致java.io.IOException: UT010029: Stream is closed解决办法
- Downie V4.6.4 for Mac 视频下载工具
- 7层WAF的一些记录
- vue事件修饰符
- 非常流行的vue库,看这一篇就够了
- 层叠样式表(CSS)3
- 大前端html学习07-HTML5的相关内容
- 层叠样式表(CSS)2(环境:MyEclipse 10)
- H5游戏架设经验分享