1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>复选框事件:全选、全不选、反选</title> 6 7 <style> 8 9 </style> 10 </head> 11 <body> 12 <input type="button" value="全选" id="selectAll" /> 13 <input type="button" value="全不选" id="selectNone" /> 14 <input type="button" value="反选" id="selectInvert" /> 15 <div id="checkboxes"> 16 <input type="checkbox" /> 17 <input type="checkbox" /> 18 <input type="checkbox" /> 19 <input type="checkbox" /> 20 <input type="checkbox" /> 21 <input type="checkbox" /> 22 <input type="checkbox" /> 23 <input type="checkbox" /> 24 </div> 25 <script> 26 var cbDiv = document.getElementById('checkboxes'); 27 var checkboxes = cbDiv.getElementsByTagName('input'); 28 //全选 29 var selectAll = document.getElementById('selectAll'); 30 selectAll.onclick = function(){ 31 for(var i = 0;i < checkboxes.length;i ++){ 32 checkboxes[i].checked = true; 33 } 34 } 35 36 //全不选 37 var selectNone = document.getElementById('selectNone'); 38 selectNone.onclick = function(){ 39 for(var i = 0;i < checkboxes.length;i ++){ 40 checkboxes[i].checked = false; 41 } 42 } 43 44 //反选 45 var selectInvert = document.getElementById('selectInvert'); 46 selectInvert.onclick = function(){ 47 for(var i = 0;i < checkboxes.length;i ++){ 48 if(checkboxes[i].checked){ 49 checkboxes[i].checked = false; 50 }else{ 51 checkboxes[i].checked = true; 52 } 53 } 54 } 55 </script> 56 </body> 57 </html>
效果: