prop()是jquery1.6中新加了一個方法,用來區分attr方法,專門用來處理DOM屬性。一些內置屬性的DOM元素或window對象,若是試圖將刪除該屬性,瀏覽器可能會產生錯誤,而prop方法則能夠避免這種錯誤發生。換言之,prop能夠說是爲了處理DOM屬性(如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected)而產生的。javascript
$(selector).prop(property) // EXP <input type=‘checkbox’> <button>查看</button> <script> $(「button」).click(function(){ $(「input」).prop(‘checked’); }); //input選中點「查看」返回true //input未選中點「查看」返回false </script>
$(selector).prop(property,value) // EXP <input type=‘checkbox’> <button>選中</button> <script> $(「button」).click(function(){ $(「input」).prop(‘checked’, true); }); </script>
$(selector).prop(property,function(index,currentvalue)) // EXP <input type="checkbox" name="issac"> <input type="checkbox" name="issac"> <input type="checkbox" name="issac"> <input type="checkbox" name="issac"> <button class="invert-checked">反選</button> <script type="text/javascript"> $(".invert-checked").click(function(){ $("input").prop('checked', function(index,oldValue){ return !oldValue; }); }); </script>
$(selector).prop({property:value, property:value,...}) <input type="checkbox」 disabled=「disabled" name="issac"> <button class="setProps」>設置多個屬性</button> <script type="text/javascript"> $(".setProps").click(function(){ $("input").prop({ ‘checked': false, ‘disabled': false }); }); </script>
prop方法和attr方法均可以以上面四種方式調用,可是prop方法比attr方法更優的是能夠更加好地處理DOM屬性;java
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() ) |
√ |
再舉一個例子:node
<input id="chk1" type="checkbox" />是否可見 <input id="chk2" type="checkbox" checked="checked" />是否可見
像checkbox,radio和select這樣的元素,選中屬性對應「checked」和「selected」,這些也屬於固有屬性,所以須要使用prop方法去操做才能得到正確的結果。jquery
$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true
若是上面使用attr方法,則會出現:瀏覽器
$("#chk1").attr("checked") == undefined $("#chk2").attr("checked") == "checked"