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

posted @ 2013-07-12 10:12  /vimer  阅读(214)  评论(0编辑  收藏  举报