jquery中的prop方法和attr方法

最近遇到一个很奇怪的问题,使用 $().attr(‘checked’)返回 undefined 。上 jquery 的官网才发现,原来是版本问题,在1.6版本之后,得使用 .prop 方法取 checked 属性。

我们看看官网 API 的说明。

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

现在来看看attribute和property的区别:attribute是一种节点(属性节点),和元素节点是一个级别的节点,或者说你可以简单的认为attribute是一个属性节点对象,而property则是对象的一个字段,可能元素节点对象的字段或属性节点对象的字段还有文本节点对象。例如属性节点对象有个property叫nodeName, 例如: var tem1 = document.getElementById("title"); var attr = tem1.getAttributeNode("id");alert(attr.nodeName);其实Dom中关于attribute和property一个非常迷惑人的地方在于,对于常见的几个attribute,例如id, class, title等,既提供了attribute的访问方式(因为它们本来就是attribute,所以肯定可以通过attribue的方式),同时为了兼容Dom1之前的写法(有时又称之DOM0),将这几种常见的attribute的值又同时保存为元素节点对象的property, 因此我们既可以通过attribue的写法 var idValue = tem1.getAttribute("id");来获取attribute的值,又可以通过property的写法来获取attribute的值,如 var idValue = tem1.id。

总结:attribute是属性节点,它有许多方法来读写它的值,如getAttrute()/setAttribute, 而property则是节点对象的一个字段或者说属性(不是attribute)。

转载于:https://www.cnblogs.com/buffoon/p/3185700.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值