<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>全选反选</title>
<script>
window.onload = function(){
//全选
//点击#checkAll,给所有的checkbox加上checked属性
var checkAll = document.getElementById("checkAll");
var checkInvert = document.getElementById("checkInvert");
var hobby = document.getElementsByClassName("hobby");//这是一个数组
var checkboxs = hobby[0].getElementsByTagName("input");
checkAll.onclick = function(){
for(var i=0;i<checkboxs.length;i++){
checkboxs[i].checked = checkAll.checked;//跟随点击事件
}
}
checkInvert.onclick = function(){
for(var i=0;i<checkboxs.length;i++){
if (checkboxs[i].checked == true){
checkboxs[i].checked = false;//跟随点击事件
}
else{
checkboxs[i].checked = true;
}
}
}
}
</script>
</head>
<body>
<h1>爱好</h1>
<input type="checkbox" id="checkAll" />全选
<input type="checkbox" id="checkInvert" />反选
<ul class="hobby">
<li><input type="checkbox" />写代码</li>
<li><input type="checkbox" />玩游戏</li>
<li><input type="checkbox" />看电影</li>
<li><input type="checkbox" />撩妹</li>
<li><input type="checkbox" />撩汉</li>
<li><input type="checkbox" />篮球</li>
<li><input type="checkbox" />羽毛球</li>
</ul>
</body>
</html>