欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Jquery全選與反選點(diǎn)擊執(zhí)行一次的解決方案

 更新時(shí)間:2015年08月14日 11:00:14   投稿:mrr  
在做項(xiàng)目時(shí)遇到一個(gè)bug,checkbox全選與反選功能,只能點(diǎn)擊一次,再點(diǎn)就不起作用了,為了解決此問題,我查找了好多資料,下面把具體解決方案整理分享給大家,需要的朋友可以參考下

代碼需求, 使用attr只能執(zhí)行一次,使用prop則完美實(shí)現(xiàn)全選和反選,獲取所有選中的項(xiàng)并把選中項(xiàng)的文本組成一個(gè)字符串。

解決方案一:

代碼如下:

<html>
<head>
  <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
</head>
<body>
  <input type="checkbox" name="chk_list[]" value="1" />1
  <input type="checkbox" name="chk_list[]" value="2" />2
  <input type="checkbox" name="chk_list[]" value="3" />3
  <input type="checkbox" name="chk_list[]" value="4" />4
  <input type="checkbox" name="chk_all" id="chk_all" />全選/取消全選
<script type="text/javascript">
  $("#chk_all").click(function(){
   // 使用attr只能執(zhí)行一次
   $("input[name='chk_list[]']").attr("checked", $(this).attr("checked")); 
   // 使用prop則完美實(shí)現(xiàn)全選和反選
   $("input[name='chk_list[]']").prop("checked", $(this).prop("checked"));
    // 獲取所有選中的項(xiàng)并把選中項(xiàng)的文本組成一個(gè)字符串
   var str = '';
   $($("input[name='chk_list[]']:checked")).each(function(){
   str += $(this).next().text() + ',';
   });
   alert(str);
  });
</script>
</body>
</html>

總結(jié):

對(duì)于HTML元素本身就帶有的固有屬性,在處理時(shí),使用prop方法。

對(duì)于HTML元素我們自己自定義的DOM屬性,在處理時(shí),使用attr方法。

參考 http://www.dbjr.com.cn/article/62308.htm

解決方案二:

問題描述:

$(".chooseall").click(function(){
 if($(".chooseall").attr("checked") == "checked"){
$("input[name='checkbox1']").removeAttr("checked","checked");
 console.log(1);
 }else{
 $("input[name='checkbox1']").attr("checked","checked");
 console.log(2);
 }
});

上面的這個(gè)代碼第一次點(diǎn)擊和第二次點(diǎn)擊,能實(shí)現(xiàn)全選和反選功能,但一遍之后就不再起作用,這是什么情況啊

除了第一個(gè)checkbox之外,其余的都是ajax動(dòng)態(tài)生成的,跟這個(gè)有關(guān)系么?console.log每次點(diǎn)擊的都能交替輸出1和2,但就是中間的代碼不能執(zhí)行。

解決方案:

removeAttr參數(shù)只需要一個(gè),removeAttr("checked")
不過建議替換成

$(".chooseall").click(function(){
 if($(".chooseall").prop("checked") == true){
 $("input[name='checkbox1']").prop("checked", false);
 console.log(1);
 }else{
 $("input[name='checkbox1']").prop("checked", false);
 console.log(2);
 }
});

或者更簡潔的,

$(".chooseall").click(function(){
 var isChecked = $(this).prop("checked");
 $("input[name='checkbox1']").prop("checked", isChecked);
});

以上是Jquery全選與反選點(diǎn)擊執(zhí)行一次的解決方案,希望對(duì)大家有所幫助。

相關(guān)文章

最新評(píng)論