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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值