今天在用JQuery的時候發現一個問題用.attr("checked")獲取checkbox的checked屬性時選中的時候可以取到值,值爲"checked"但沒選中獲取值就是undefined.
解決這個文章我參考了這個帖子:
http://bugs.jquery.com/ticket/9812
爲什麼jquery 1.6+增加了.prop()方法,因爲在有些瀏覽器中比如說只要寫disabled,checked就可以了,而有的要寫成disabled = "disabled",checked="checked"。所以,從1.6開始,jq提供新的方法“prop”來獲取這些屬性。
以前我們使用attr獲取checked屬性時返回"checked"和"",現在使用prop方法獲取屬性則統一返回true和false。
那麼,什麼時候使用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() ) | √ |