JQuery中prop與attr的區別
問題
爲了實現複選框的全選和全不選的功能,需要通過JQuery來動態的設置checkbox的checked狀態(即選中與否)。最初使用.attr()
方法
if(first.checked)
{
$("input[name='checkboxLeave']").attr('checked', false);
}
else
{
$("input[name='checkboxLeave']").attr('checked', true);
}
在切換一輪之後便再無反應,語句依舊執行但網頁上的元素卻沒有相應的改變。
解決方法
換成.prop()
方法問題就解決了。
if(first.checked)
{
$("input[name='checkboxLeave']").prop('checked', false);
}
else
{
$("input[name='checkboxLeave']").prop('checked', true);
}
原因
問題的關鍵點就在於.attr()
和.prop()
之前的區別。
下面是關於jQuery1.6和1.6.1中Attributes模塊變化的描述,以及.attr()方法和.prop()方法的首選使用:
Attributes模塊的變化是移除了attributes和properties之間模棱兩可的東西,但是在jQuery社區中引起了一些混亂,因爲在1.6之前的所有版本中都使用一個方法(.attr())來處理attributes和properties。但是老的.attr()方法有一些bug,很難維護。jQuery1.6.1對Attributes模塊進行了更新,並且修復了幾個bug。
elem.checked true (Boolean) Will change with checkbox state
$(elem).prop("checked") true (Boolean) Will change with checkbox state
elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state
if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
這三個都是返回Boolean值。
爲了讓jQuery1.6中的.attr()
方法的變化被理解的清楚些,下面是一些使用.attr()的例子,雖然在jQuery之前的版本中能正常工作,但是現在必須使用.prop()
法代替:
首先,window或document中使用.attr()方法在jQuery1.6中不能正常運行,因爲window和document中不能有attributes。它們包含properties(比如:location或readyState),必須使用.prop()方法操作或簡單地使用javascript原生的方法。在jQuery1.6.1中,window和document中使用.attr()將被自動轉成使用.prop,而不是拋出一個錯誤。
其次,checked,selected和前面提到的其它boolean attributes,因爲這些attributes和其相應的properties之間的特殊關係而被特殊對待。基本上,一個attribute就是以下html中你看到的:
<input type=”checkbox” checked=”checked”>
boolean attributes,比如:checked,僅被設置成默認值或初始值。在一個checkbox的元素中,checked attributes在頁面加載的時候就被設置,而不管checkbox元素是否被選中。
properties就是瀏覽器用來記錄當前值的東西。正常情況下,properties反映它們相應的attributes(如果存在的話)。但這並不是boolean attriubutes的情況。當用戶點擊一個checkbox元素或選中一個select元素的一個option時,boolean properties保持最新。但相應的boolean attributes是不一樣的,正如上面所述,它們僅被瀏覽器用來保存初始值。
在jQuery1.6中,如果使用下面的方法設置checked:
$(“:checkbox”).attr(“checked”, true);
將不會檢查checkbox元素,因爲它是需要被設置的property,但是你所有的設置都是初始值。
下面是一些attributes和properties的列表,正常情況下,應該使用其對應的方法(見下面的列表)來取得和設置它們。下面的是首用法,但是.attr()方法可以運行在所有的attributes情況下。
注意:一些DOM元素的properties也被列在下面,但是僅運行在新的.prop()方法中
P.S.
.attr()和.prop()都不應該被用來取值/設值。使用.val()方法代替(即使使用.attr(“value”,”somevalue”) 可以繼續運行,就像1.6之前做的那樣)