<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>全选反选</title> </head> <body> <div id="hobby"> <input type="checkbox" value="1"/>唱歌 <input type="checkbox" value="2"/>跳舞 <input type="checkbox" value="3"/>rap <input type="checkbox" value="4"/>篮球 </div> <input type="button" onclick="all_check()" value="全选"/> <input type="button" onclick="no_check()" value="不选"/> <input type="button" onclick="toggle_check()" value="反选"/> </body> </html> <script> hobby = document.getElementById('hobby') var ainput = hobby.getElementsByTagName('input') var len = ainput.length function all_check() { for(var i=0;i<len;i++) { //ainput[i] checked值选中 ainput[i].checked = true } } function no_check() { for(var i=0;i<len;i++) { ainput[i].checked = false } } function toggle_check() { for(var i=0;i<len;i++) { if(ainput[i].checked == true) { ainput[i].checked = false }else { ainput[i].checked = true } } } </script>
测试如下