jQuery attr与prop的区别
sshong 发表于2013年9月23日 11:03:11 更新于2013年9月23日 12:16:01
一直很疑惑prop与attr的区别,今天特意研究了以下,备查如下。
jQuery文档里有一段很精辟的描述:
prop是指动态改变一个DOM元素的状态而不改变HTML的源码,如input元素的value、disabled、checked等,通过prop来改变disabled、checked的值,用val来改变value值。
通过attr改的属性会反应到html源码里,而prop不会。如:
看jQuery源码:
attr用的是element的setAttribute、getAttribute方法,prop用的是element.***。
总之,获取、更改checked、disabled、selected用prop(不要removeProp这几个内置的属性),获取、更改value用val,其他的用attr。
jQuery文档里有一段很精辟的描述:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute.
Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox.
The .prop() method should be used to set disabled and checked instead of the .attr() method.
The .val() method should be used for getting and setting value.
prop是指动态改变一个DOM元素的状态而不改变HTML的源码,如input元素的value、disabled、checked等,通过prop来改变disabled、checked的值,用val来改变value值。
通过attr改的属性会反应到html源码里,而prop不会。如:
F12查看一下,会发现testAttr已经加到html源码里,而prop则不会,但是prop确实能取到这个属性,是不是有点$.data的赶脚,但是只能设置string、number、bool值。$('input[name="reports_mode"]').prop('testProp', 'prop');
$('input[name="reports_mode"]').attr('testAttr', 'attr'); alert($('input[name="reports_mode"]').prop('testProp') + $('input[name="reports_mode"]').attr('testAttr'));
换句话讲,用attr改checked实际上改的不是checkbox的状态,而是更改了defaultChecked的属性值,即仅仅是设置了初始值,而prop改checked则会更改checkbox的状态。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" ) )
The same is true for other dynamic attributes, such as selected and value.
看jQuery源码:
attr用的是element的setAttribute、getAttribute方法,prop用的是element.***。
总之,获取、更改checked、disabled、selected用prop(不要removeProp这几个内置的属性),获取、更改value用val,其他的用attr。
评论
暂无评论添加评论
分类
琐碎文字 As3&Flex RIA UG English CodingArt C++ PHP Webserver E音乐盒 Unity3d C# JS&Html5 Tools mobile golang AI 最近发表
- claude code / codex的一些配置(2026年5月5日 17:38:10)
- 2026年5月5日(2026年5月5日 17:27:39)
- js的锁以及异步调用相关(2024年11月30日 10:58:51)
- golang学习之函数/方法/接口(2022年1月6日 17:50:24)
- golang学习之零值(2022年1月6日 16:38:10)
- hello, 2018(2018年1月15日 22:47:25)
- 字体类型名词解释(2015年1月18日 11:29:14)
- 获取mysql表注释以及列注释(2014年11月13日 15:56:32)
- php连接ms sql数据库的一些问题(2014年9月15日 20:32:14)
- virtualbox虚拟网络:NAT&bridge桥接网络(2014年8月25日 22:51:35)
最近回复