jquery中prop()方法和attr()方法的區別淺析

來源:互聯網
上載者:User

jquery1.6中新加了一個方法prop(),一直沒用過它,官方解釋只有一句話:擷取在匹配的元素集中的第一個元素的屬性值。

大家都知道有的瀏覽器只要寫disabled,checked就可以了,而有的要寫成disabled = "disabled",checked="checked",比如用attr("checked")擷取checkbox的checked屬性時選中的時候可以取到值,值為"checked"但沒選中擷取值就是undefined。

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() )  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.