標籤: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()兩種方法