javascript代码:
function selectAll() { //获得全选 var checkAll = document.getElementById("checkAll"); //所有爱好 var hobbies = document.getElementsByName("hobby"); //当其选中时,所有爱好选中 if (checkAll.checked) { for (var i = 0; i < hobbies.length; i++) { hobbies[i].checked = checkAll.checked; } } } //为所有的爱好注册事件 window.onload = function () { var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { //为每个爱好注册点击事件 hobbies[i].onclick = hobbyClick; } } function hobbyClick() { var checkAll = document.getElementById("checkAll"); var noneAll = document.getElementById("noneAll"); var hobbies = document.getElementsByName("hobby"); //假定所有爱好都被选中 var flag = true; for (var i = 0; i < hobbies.length; i++) { if (!hobbies[i].checked) { flag = false; //break; } else { noneAll.checked = false; } } checkAll.checked = flag; } function reserveAll() { var checkAll = document.getElementById("checkAll"); var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { hobbies[i].checked = !hobbies[i].checked; } //设置每个爱好后,检查其所有状态 hobbyClick(); } function noneAll() { var checkAll = document.getElementById("checkAll"); var hobbies = document.getElementsByName("hobby"); for (var i = 0; i < hobbies.length; i++) { hobbies[i].checked = false; } //设置每个爱好后,检查其所有状态 hobbyClick(); }
网页内容:
<input type="checkbox" id="checkAll" οnclick="selectAll()" />全选<input type="checkbox" id="reserveAll" οnclick="reserveAll()" />反选<input type="checkbox" id="noneAll" οnclick="noneAll()" />全不选<br /> <input type="checkbox" id="Checkbox1" name="hobby" />书法<input type="checkbox" name="hobby" id="Checkbox2" />足球<input name="hobby" type="checkbox" id="Checkbox3" />音乐<input name="hobby" type="checkbox" id="Checkbox5" />打飞机<input name="hobby" type="checkbox" id="Checkbox6" />喝啤酒
<div id="songs"><input type="checkbox" />两只老虎<input type="checkbox" />两只蝴蝶<input type="checkbox" />狼<input type="checkbox" />春天里<input type="checkbox" />青春<br /><input type="button" value="全选" οnclick="allitemselect()" /><input type="button" value="全不选" οnclick="noneitemselect()" /><input type="button" value="反选" οnclick="someitemselect()" /></div>
jquery版:
$(function () { $("#songs input[value=全选]").click(function () { $("#songs input[type=checkbox]").attr("checked", true); }); $("#songs input[value=全不选]").click(function () { $("#songs input[type=checkbox]").attr("checked", false); }); $("#songs input[value=反选]").click(function () { $("#songs input[type=checkbox]").each(function () { $(this).attr("checked", !$(this).attr("checked")); //this.checked = !this.checked; }); }); });