As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()method.
注意最後兩句話,說什麼.attr() 不能用於普通對象,數組,窗口,文檔什麼玩意的,要重新獲取改變dom屬性,用.prop()方法。
那麼,什麼時候使用attr(),什麼時候使用prop()?
1.添加屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();
項目中jquery升級的時候大家要注意這點!
以下是官方建議attr(),prop()的使用:
Attribute/Property |
.attr() |
.prop() |
---|---|---|
accesskey | √ | |
align | √ | |
async | √ | √ |
autofocus | √ | √ |
checked | √ | √ |
class | √ | |
contenteditable | √ | |
draggable | √ | |
href | √ | |
id | √ | |
label | √ | |
location ( i.e. window.location ) | √ | √ |
multiple | √ | √ |
readOnly | √ | √ |
rel | √ | |
selected | √ | √ |
src | √ | |
tabindex | √ | |
title | √ | |
type | √ | |
width ( if needed over .width() ) |
√ |