概述
做項(xiàng)目過程中关噪,你可可能會(huì)發(fā)現(xiàn)使用attr將checkbox設(shè)置checked并不能生效了慕蔚,這是因?yàn)樵趈Query1.6開始新增了一個(gè)方法 prop()。
概念
prop在官方文檔中的解釋是:獲取匹配的元素集中第一個(gè)元素的屬性(property)值或設(shè)置每一個(gè)匹配元素的一個(gè)或多個(gè)屬性稼虎。
Attributes vs Properties
attributes和properties之間的差異在特定情況下是很重要庐杨。jQuery 1.6之前 选调,.attr()方法在取某些 attribute 的值時(shí),會(huì)返回 property 的值灵份,這就導(dǎo)致了結(jié)果的不一致仁堪。從 jQuery 1.6 開始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值填渠。
例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 應(yīng)使用.prop()方法進(jìn)行取值或賦值弦聂。 在jQuery1.6之前,這些屬性使用.attr()方法取得氛什,但是這并不是元素的attr屬性莺葫。他們沒有相應(yīng)的屬性(attributes),只有特性(property)枪眉。
例如捺檬,考慮一個(gè)DOM元素的HTML標(biāo)記中定義的 ,并假設(shè)它是一個(gè)JavaScript變量命名的elem :
elem.checked true (Boolean) 將隨著復(fù)選框狀態(tài)的改變而改變
$(elem).prop(“checked”) true (Boolean) 將隨著復(fù)選框狀態(tài)的改變而改變
elem.getAttribute(“checked”) “checked” (String) 復(fù)選框的初始狀態(tài);不會(huì)改變
$(elem).attr(“checked”) (1.6) “checked” (String) 復(fù)選框的初始狀態(tài);不會(huì)改變
$(elem).attr(“checked”) (1.6.1+) “checked” (String) 將隨著復(fù)選框狀態(tài)的改變而改變
$(elem).attr(“checked”) (pre-1.6) true (Boolean) 將隨著復(fù)選框狀態(tài)的改變而改變
prop
.prop()方法設(shè)置屬性值非常方便贸铜,尤其是對(duì)于需要使用一個(gè)函數(shù)設(shè)置多個(gè)屬性值或是一次性設(shè)置多個(gè)屬性值的情況堡纬。當(dāng)設(shè)置selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 或 defaultSelected必須使用這個(gè)方法。從jQuery1.6開始蒿秦,這些屬性可以不再使用.attr()方法來設(shè)置烤镐。他們沒有相應(yīng)的屬性(attributes),只有屬性(property)渤早。
Properties 屬性一般影響 DOM 元素的動(dòng)態(tài)狀態(tài)并不會(huì)改變序列化的 HTML attribute 屬性职车。例如,input 元素的 value 屬性鹊杖,input 和 按鈕 元素的 disabled 屬性, 以及 checkbox 的 checked 屬性悴灵。應(yīng)該使用 .prop() 方法設(shè)置 disabled 和 checked 屬性,而不是使用 .attr() 方法骂蓖。 .val() 方法應(yīng)該用于存取 value 值积瞒。
例子
所以我們?cè)僭O(shè)置checkbox的checked時(shí),使用prop就可以正常設(shè)置了登下。
$(“#chekbox”).prop(“checked”,true);
$(“#chekbox”).prop(“checked”,false);
API文檔鏈接:http://api.jquery.com/prop/