<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><title>dom查询练习二</title><link rel="stylesheet" href="../browser_default_style/reset.css"><style>form {margin: 10px 0px 0px 10px;}p {display: inline-block;}input{color: green;}span {font-family: 'Courier New', Courier, monospace;}.li {margin: 5px 0px 10px 0px;}</style><script>window.onload = function () {// 获取多选框var SelectALL_OrNot = document.getElementsByName("AllSelect_NoneSelect")[0];var item = document.getElementsByName("item");// 为 "第一个按钮:全选" 绑定事件var AllSelect = document.getElementById("AllSelect");AllSelect.onclick = function () {for (var i = 0; i < item.length; i++) {item[i].checked = true;}SelectALL_OrNot.checked = true;}// 为 "第二个按钮:全不选" 绑定事件var NoneSelect = document.getElementById("NoneSelect");NoneSelect.onclick = function () {for (var i = 0; i < item.length; i++) {item[i].checked = false;}SelectALL_OrNot.checked = false;}// 为 "第三个按钮:反选" 绑定事件var AgainestSelect = document.getElementById("AgainestSelect");AgainestSelect.onclick = function () {for (var i = 0; i < item.length; i++) {// 相当于:if(item[i].checked == true){item[i].checked = false;} else item[i].checked = true; item[i].checked = !item[i].checked;}}// 为 "第四个按钮:提交" 绑定事件var Submit = document.getElementById("Submit");Submit.onclick = function () {for (var i = 0; i < item.length; i++) {if (item[i].checked == true) {alert(item[i].value);}}}// 为 "多选框:全选/全不选" 绑定事件// 条件:四个多选框一旦有一个没选,则 "全选/全不选"多选框 设置为不选中(false)状态SelectALL_OrNot.onclick = function () {for (var i = 0; i < item.length; i++) {// "全选/全不选"多选框 一旦设置选中,则 "所有列表项" 都选中;反之也如此。item[i].checked = SelectALL_OrNot.checked;}}// 为 "多选框:列表项" 绑定事件// 条件:1、四个多选框都选中,则 "全选/全不选"多选框 默认设置为选中(true)状态;// 条件:2、一旦有一个没选中则设置为不选中(false)状态。for (var i = 0; i < item.length; i++) {item[i].onclick = function () {SelectALL_OrNot.checked = true;for (j = 0; j < item.length; j++) {if (item[j].checked == false) {SelectALL_OrNot.checked = false;break;}}}}}</script>
</head><body><form action=""><p>你爱好的运动是?</p><input type="checkbox" name="AllSelect_NoneSelect" class="All"><span>全选/全不选</span><br><p class="li"><input type="checkbox" name="item" value="足球">足球<input type="checkbox" name="item" value="篮球" checked>篮球<input type="checkbox" name="item" value="羽毛球">羽毛球<input type="checkbox" name="item" value="乒乓球">乒乓球</p><br><input type="button" id="AllSelect" value="全选"><input type="button" id="NoneSelect" value="全不选"><input type="button" id="AgainestSelect" value="反选"><input type="button" id="Submit" value="提交"></form>
</body></html>