jquery 中attr和prop的区别

在jQuery API中也有专门解释:node

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

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

<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没有值,这点儿对其它布尔类型的属性同样适用。orm

然而关于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也适用。blog

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

使用场景

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

相关文章
相关标签/搜索