首页 > prop()跟attr()的核心区别是什么??

prop()跟attr()的核心区别是什么??

为什么相同的功能要分这两种用法呢?他们的核心区别是什么?


attr是html文档对应标签的属性
prop是dom元素对应节点的属性


要不看看这个文档?jquery-prop


这是官方文档的解释:

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.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

详细请看Jquery_.attr()_Attributes vs. Properties


<input type="checkbox" checked="checked" />
$(elem).attr("checked");//"checked" (String) 
$(elem).prop("checked");//    true (Boolean) 
判断一个复选框是否被选中:
if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )

prop()是jQuery1.6加进来的,prop是property, attr是attribute,这两个词在汉语中都是可以翻译为属性,因此更加混乱。 既然有了attr()为何还来prop()?

主要原因是attr()在绝大部分情况下返回的都是字符串,另外你用attr()去获取一些没有设置的属性时,它会返回undefined,而不是系统默认值。attr()在获取属性上有它的局限性,所以才有了prop()。

关于这个问题、及property 和 attribute的区别,可以看看这篇文字
http://stackoverflow.com/questions/5874652/prop-vs-attr

【热门文章】
【热门文章】