12allChoose.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="checkbox" name="all" id="" />全选 <input type="checkbox" name="fx" id="" />反选 <input type="checkbox" name="h" id="" /> <input type="checkbox" name="h" id="" /> <input type="checkbox" name="h" id="" /> <input type="checkbox" name="h" id="" /> <input type="checkbox" name="h" id="" /> <input type="checkbox" name="h" id="" /> <script> // 全选功能 var all = document.getElementsByName("all")[0]; var hs = document.getElementsByName("h"); var fx = document.getElementsByName("fx")[0]; all.onclick = function () { //alert(this.checked); var flag = this.checked; // 让其他复选框与全选复选框状态一致 for (var i = 0; i < hs.length; i++) { hs[i].checked = flag; } } // 反选 fx.onclick = function() { //让其他复选框与自己原来状态相反 for(var i=0; i<hs.length; i++) { if(hs[i].checked) { hs[i].checked = false; } else { hs[i].checked = true; } } }
//实现全部复选框选中后,全选的复选框被选中,否则未被选中 var count = 0; for(var i=0; i<hs.length; i++) { hs[i].onclick = function() { // 统计复选框选中个数 count = 0; for(var j=0; j<hs.length; j++) { if(hs[j].checked) { count++; } } if(count === hs.length) { all.checked = true; } else { all.checked = false; } } } </script> </body> </html>