jquery 中attr和prop的区别

在jQuery API中也有专门解释:

Attributes VS. Properties

在一些特殊的情况下,attributes和properties的区别非常大。在jQuery1.6之前,.attr()方法在获取一些attributes的时候使用了property值,这样会导致一些不一致的行为。在jQuery1.6中,.prop()方法提供了一中明确的获取property值得方式,这样.attr()方法仅返回attributes。

比如,selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和defaultSelected应该使用.prop()方法获取/设置值。 在jQuery1.6之前这些不属于attribute的property需要用.attr()方法获取。这几个并没有相应的attibute,只有property。

关于布尔类型 attributes,比如一个这样的HTML标签,它在JavaScript中变量名为elem

<input type="checkbox" checked="checked" />
elem.checked true (Boolean) Will change with checkbox state
$( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" ) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state

根据W3C forms specification,checked属性是一个布尔值,这就意味着只要checked属性在HTML中表现出来了,那么相应的property就应该是true,即使checked没有值,这点儿对其它布尔类型的属性一样适用。

然而关于checked 属性需要记住的最重要的一点是:它和checked property并不是一致的。实际上这个attribute和defaultChecked property一致,而且只应该用来设置checkbox的初始值。checked attribute并不随着checkedbox的状态而改变,但是checked property却跟着变。因此浏览器兼容的判断checkebox是否被选中应该使用property

if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )

这对其它一些类似于selected、value这样的动态attribute也适用。

在IE9之前版本中,如果property没有在DOM元素被移除之前删除,使用.prop()方法设置DOM元素property(简单类型除外:number、string、boolean)的值会导致内存泄露。为了安全的设置DOM对象的值,避免内存泄露,可以使用.data()方法。

使用场景

其实明白了上面讲的内容,什么时候该使用.attr()什么时候该使用 .prop()就很清楚了,不过还是传一张坊间很流行的图

转自:http://www.cnblogs.com/dolphinX/p/3348582.html

原文地址:https://www.cnblogs.com/tv151579/p/3451175.html