今天同事 讓幫忙調試一個checkbox只選中一個的方法,代碼如下:
<table id="table_platform" class="table table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>平台代碼</th> <th>平台名稱</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" id="batch1" name="ptcode" value="1"></td> <td>選項2</td> <td>選項2</td> </tr> <tr> <td><input type="checkbox" id="batch2" name="ptcode" value="2"></td> <td>選項3</td> </tr> <tr> <td><input type="checkbox" id="batch3" name="ptcode" value="3"></td> <td>選項4</td> </tr> </tbody> </table> <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script> <script>//$("p").siblings(".selected") var EleInput=$("[name = ptcode]:checkbox")//;$("#table_platform input") ; EleInput.each(function(index, element) { $(element).bind("click",function(){ EleInput.attr("checked",false); $(this).attr("checked",true); }); }); </script>
好的,靜態demo調試 ~ 運行~ 無問題。以為都結束了,但是放到項目出現了,
checkbox標簽已有checked=checked但是不顯示勾選,查看圖片:
於是乎 就開始網上查找 ,解決方法 就是將 $("...").attr("checked", true) 改為 $("...").prop("checked", true),問題解決;
那么這樣解決的原因是什么呢??
首先來了解下jquey中的attr()函數和prop()函數;
attr()是處理 attribute的值的,而prop()是處理 property 的值的 ,jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值時,會返回 property 的值,這就導致了結果的不一致。
- property是DOM中的屬性,是JavaScript里的對象;
- attribute是HTML標簽上的特性,它的值只能夠是字符串;
從 jQuery 1.6 開始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值,那么歸根結底,就是在處理 attribute 和 property。 很多attribute節點有一個相應的property屬性,因而attribute和property很容易被混淆在一起,
1) 如某個div元素中的id和class既是attribute也有property,不管哪種方式都可以訪問和修改,但是對於自定義的attribute節點,或者自定義property,兩者就沒有關系了(但是在IE6-7中,兩者還是一樣的,好奇葩的,但願我們都能早日拋棄IE8以下的),
2) 需要注意的是,對於checked特性(attribute)不是對應它checked屬性(property),attribute實際對應的是defaultChecked屬性,而且僅用於設置復選框最初的值,checked的attribute不會因為復選框的狀態而改變,而checked的property會因為復選框的狀態而改變,所以在.attr()函數中,就算設置成 了.attr("checked", true),也只是用來存儲默認或者選中屬性的默認值,卻並不改變該復選框被選中和選中,這就是為什么 checkbox標簽已有checked=checked但是不顯示勾選 的原因所在