您的位置:首页 > Web前端 > JQuery

jquery中prop()方法和attr()方法的区别

2014-01-14 11:56 666 查看
jquery1.6中新加了一个方法prop(),一直没用过它,官方解释只有一句话:获取在匹配的元素集中的第一个元素的属性值。

官方例举的例子感觉和attr()差不多,也不知道有什么区别,既然有了prop()这个新方法,不可能没用吧,那什么时候该用attr(),什么时候该用prop()呢?

大家都知道有的浏览器只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked",比如用attr("checked")获取checkbox的checked属性时选中的时候可以取到值,值为"checked"但没选中获取值就是undefined。

jq提供新的方法“prop”来获取这些属性,就是来解决这个问题的,以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。

那么,什么时候使用attr(),什么时候使用prop()?

1.添加属性名称该属性就会生效应该使用prop();

2.是有true,false两个属性使用prop();

3.其他则使用attr();

项目中jquery升级的时候大家要注意这点!

以下是官方建议attr(),prop()的使用:

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值。



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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: