<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> //全选方法 function f1() { var inputs = document.getElementsByTagName("input"); var cheAll = event.srcElement; for (var i = 0; i < inputs.length; i++) { if (inputs[i].id != "cheRev") { inputs[i].checked = cheAll.checked; } } } //反选方法 function f2() { var inputs = document.getElementsByTagName("input"); //每一个checkbox取反 for (var i = 0; i < inputs.length; i++) { if (inputs[i].id != "checkAll" && inputs[i].id != "cheRev") { inputs[i].checked = !inputs[i].checked; } } //如果此时全部选中,也要将全选取反,反之亦然 isCheckedAll(); } //为每一个非全选的checkbox添加点击事件 window.onload = function () { var inputs = document.getElementsByTagName("input"); for (var i = 0; i < inputs.length; i++) { if (inputs[i].id != "checkAll" && inputs[i].id != "cheRev") { inputs[i].onclick = isCheckedAll; } } } //判断此时是否是全选,如果是则勾上全选按钮,如果不是,则取消勾取全选按钮。 function isCheckedAll() { var inputs = document.getElementsByTagName("input"); //假设全都被选中 var isChecked = true; for (var j = 0; j < inputs.length; j++) { if (inputs[j].id != "checkAll" && inputs[j].id != "cheRev") { if (!inputs[j].checked) { isChecked = false; break; } } } var checkAll = document.getElementById("checkAll"); checkAll.checked = isChecked; } </script> </head> <body> <input id="checkAll" type="checkbox" onclick="f1()" value="" />全选 <input id="cheRev" type="button" value="反选" onclick="f2()" /><br/> <input id="one" type="checkbox" name="" />吃饭<br /> <input id="two" type="checkbox" name="" />睡觉<br /> <input id="three" type="checkbox" name="" />打豆豆<br /> </body> </html>