jQuery屬性選取器.attr()和.prop()兩種方法

來源:互聯網
上載者:User

標籤:des   blog   http   io   ar   使用   java   sp   for   

在判斷表單單選框是否被選中時,通常會想到使用$(‘#checkbox‘).attr(‘checked‘)來判斷,但在一些情況下,你會發現這種方法並不管用,得到的是undefined。

原來jQuery在1.6版本以後對屬性選取器做了一些調整,分為.attr()和.prop()兩種方法。為的是區分元素attributes和properties之間模稜兩可的東西。

那麼它們之間有什麼區別呢?

官方的解釋是:

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

其實也就是對DOM元素中的特性(attribute)和屬性(property)做了明確的區分。

所以判斷checkbox是否被選中,正確的方法應該是:

 $(‘#checkbox‘).prop(‘checked‘); // jQuery 1.6+ $(‘#checkbox‘).attr(‘checked‘); // 在 1.6.1 和 <=1.5 中使用,但不包括 1.6 的版本 $(‘#checkbox‘).is(‘:checked‘); // 所有版本 $("#ck:checked").length==1; // 所有版本
網友的百度問答:
prop()擷取匹配的元素的屬性值。
這個方法是jquery1.6以後出來的,用來區別之前的.attr()方法.

區別最大的一點就是:布爾型的屬性,1.6以後都是用.prop()方法就好了。
這個布爾型的屬性,再解釋一下,是屬性值只有true|false的屬性。
還有種情況就是只添加屬性名稱,不需要寫屬性值的就可以生效的也同樣使用.prop()方法。比如:checked、disable這樣的,其實它們說到底還是屬於布爾型的屬性。

1.添加屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();

<參考:http://www.vipaq.com/Article/View/blog/356.html>

jQuery屬性選取器.attr()和.prop()兩種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.