在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()就很清楚了,不過仍是傳一張坊間很流行的圖內存