概述
做項(xiàng)目過(guò)程中,你可可能會(huì)發(fā)現(xiàn)使用attr將checkbox設(shè)置checked并不能生效了,這是因?yàn)樵趈Query1.6開(kāi)始新增了一個(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 開(kāi)始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值。
例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 應(yīng)使用.prop()方法進(jìn)行取值或賦值。 在jQuery1.6之前,這些屬性使用.attr()方法取得,但是這并不是元素的attr屬性。他們沒(méi)有相應(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開(kāi)始,這些屬性可以不再使用.attr()方法來(lái)設(shè)置。他們沒(méi)有相應(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/