jQuery attr与prop的区别
sshong 发表于2013年9月23日 11:03:11 更新于2013年9月23日 12:16:01
一直很疑惑prop与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不会。如:
$('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'));
F12查看一下,会发现testAttr已经加到html源码里,而prop则不会,但是prop确实能取到这个属性,是不是有点$.data的赶脚,但是只能设置string、number、bool值。
attr

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.
换句话讲,用attr改checked实际上改的不是checkbox的状态,而是更改了defaultChecked的属性值,即仅仅是设置了初始值,而prop改checked则会更改checkbox的状态。

看jQuery源码:
attr用的是element的setAttribute、getAttribute方法,prop用的是element.***。

总之,获取、更改checked、disabled、selected用prop(不要removeProp这几个内置的属性),获取、更改value用val,其他的用attr。
标签:无分类:JS&Html5阅读:3096
评论
暂无评论
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅