標籤:
今天編寫JS指令碼時,遇到如下的問題。
下面是原始碼:
<script src="../Scripts/jquery-2.1.3.js"></script><script type="text/javascript">$(function(){ //全選 $("#CheckedAll").click(function(){ $(‘[name=items]:checkbox‘).attr(‘checked‘, true); }); //全不選 $("#CheckedNo").click(function(){ $(‘[name=items]:checkbox‘).attr(‘checked‘, false); });<script>
用瀏覽器運行,結果出現第一次點擊全選按鈕,checkbox能夠正常顯示,但是點了全不選後,再去點擊就失效了。
網上查了後得到原因,做個筆記。
這裡其實是版本的原因,在jQuery1.6版之前完全沒問題,我這裡用的2.1.3版本。因此這個版本不能再使用attr()了,而是用另外一個類似的方法prop()。將上面的語句修改成如下即可正確運行。
$(‘[name=items]:checkbox‘).prop(‘checked‘, true); $(‘[name=items]:checkbox‘).prop(‘checked‘, false);
那麼這兩者又有什麼區別呢?
prop是jQuery1.6版本新增的方法,用法和attr十分相似。
attr:屬性,如“name,id” prop:特性,如"selectedIndex,tagname,nodename"
在jQuery1.6版本之後,可以通過attr方法去獲得屬性,通過prop方法去獲得特性。
$(‘#football‘).prop("checked"); //true
$(‘#football‘).attr("checked"); //undefined
以下內容屬於轉載,原文地址:http://gxxsite.com/content/view/id/135.html
通過分析attr和prop的源碼,得知:
attr方法裡面,最關鍵的兩行代碼,elem.setAttribute( name, value + “” )和ret = elem.getAttribute( name ),很明顯的看出來,使用的DOM的API setAttribute和getAttribute方法操作的屬性元素節 點。
而prop方法裡面,最關鍵的兩行代碼,return ( elem[ name ] = value )和return elem[ name ],你可以理解成這樣document.getElementById(el)[name] = value,這是轉化成JS對象的一個屬性。
引入兩個例子:
<input type="checkbox" id="test" abc="111" />
$(function(){ el = $("#test"); console.log(el.attr("style")); //undefined console.log(el.prop("style")); //CSS Style Declaration對象 console.log(document.getElementById("test").style); //CSS Style Declaration對象});
1、el.attr(“style”)輸出undefined,因為attr是擷取的這個對象屬性節點的值,很顯然此時沒有這個屬性節點,自然輸出undefined
2、el.prop(“style”)輸出CSS Style Declaration對象,對於一個DOM對象,是具有原生的style對象屬性的,所以輸出了style對象
3、至於document.getElementById(“test”).style和上面那條一樣
el.attr("abc","111")console.log(el.attr("abc")); //111console.log(el.prop("abc")); //undefined
首先用attr方法給這個對象添加abc節點屬性,值為111,可以看到html的結構也變了
1、el.attr(“abc”)輸出結果為111,再正常不過了
2、el.prop(“abc”)輸出undefined,因為abc是在這個的屬性節點中,所以通過prop是取不到的
我們再接著來:
el.prop("abc", "222");console.log(el.attr("abc")); //111console.log(el.prop("abc")); //222
我們再用prop方法給這個對象設定了abc屬性,值為222,可以看到html的結構是沒有變化的。輸出的結果就不解釋了。
上面已經把原理講清楚了,什麼時候用什麼就可以自己把握了。
提一下,在遇到要擷取或設定checked,selected,readonly和disabled等屬性時,用prop方法顯然更好,比如像下面這樣:
<input type="checkbox" id="test" checked="checked" />
console.log(el.attr("checked")); //checkedconsole.log(el.prop("checked")); //trueconsole.log(el.attr("disabled")); //undefinedconsole.log(el.prop("disabled")); //false
顯然,布爾值比字串值讓接下來的處理更合理。
PS一下,如果你有JS效能潔癖的話,顯然prop的效能更高,因為attr需要訪問DOM屬性節點,訪問DOM是最耗時的。這種情況適用於多選項全選和反選的情況。
補充一張圖,這樣就很清晰了:
【jQuery】CheckBox使用attr全選無法正確顯示