复选框的全选反选实现(即购物车的复选框实现)

html页面

  1. <!doctype html>  
  2. <html lang="en">  
  3.     <head>  
  4.         <meta charset="UTF-8">  
  5.         <title>测试页面</title>  
  6.         <script src = "jquery.js"></script>  
  7.         <script src = "test.js"></script>  
  8.     </head>  
  9.     <body>  
  10.         <input type = "checkbox" id = "allCheck"/>全选</th><br/>  
  11.         <input type = "checkbox" name = "check"/></th>  
  12.         <input type = "checkbox" name = "check"/></th>  
  13.         <input type = "checkbox" name = "check"/></th>  
  14.         <input type = "checkbox" name = "check"/></th>  
  15.     </body>  
  16. </html>  

js代码

第一种方式 (有点不靠谱)

  1. //全选框  
  2. $("#allCheck").click(function(){  
  3. //console.log($(this).get(0).checked);
    console.log($(this).is(":checked"));
    //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
    //console.log($(this).attr('checked'));
    if($(this).is(":checked")){    if($(this).attr("checked")){  

  4.         $("input[name='check']").attr("checked",true);  
  5.     }else{  
  6.         $("input[name='check']").attr("checked",false);  
  7.     }  
  8. })  
  9. //单选框  
  10. $("input[name='check']").change(function(){  
  11.     if($("input[name='check']").not("input:checked").size() <= 0){  
  12.         $("#allCheck").attr("checked",true);  
  13.     }else{  
  14.         $("#allCheck").attr("checked",false);  
  15.     }  
  16. })  

第二种方式

  1. 全选框  
  2. $("#allCheck").click(function(){  
  3.     $("input[name='check']").prop("checked",this.checked);  
  4. })  
  5. //单选框  
  6. $("input[name='check']").change(function(){  
  7.     if($("input[name='check']").not("input:checked").size() <= 0){  
  8.         $("#allCheck").prop("checked",true);  
  9.     }else{  
  10.         $("#allCheck").prop("checked",false);  
  11.     }  
  12. })  

第三种方式(原生js)

  1. //全选框  
  2. $("#allCheck").click(function(){  
  3.     var a = document.getElementById("allCheck");  
  4.     var b = document.getElementsByName("check");  
  5.     if(a.checked){  
  6.         for(var i = 0; i < b.length; i++){  
  7.             b[i].checked = true;  
  8.         }  
  9.     }else{  
  10.         for(var i = 0; i < b.length; i++){  
  11.             b[i].checked = false;  
  12.         }  
  13.     }  
  14. })  
  15. //单选框  
  16. $("input[name='check']").click(function(){  
  17.     var flag = true;  
  18.     var a = document.getElementById("allCheck");  
  19.     var b = document.getElementsByName("check");  
  20.     for(var i = 0; i < b.length; i++){  
  21.         if(!b[i].checked){  
  22.             flag = false;  
  23.             break;  
  24.         }  
  25.     }  
  26.     a.checked = flag;  
  27. }); 
原文地址:https://www.cnblogs.com/robbinluobo/p/8302075.html