<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>checkbox2</title>
</head>
<body>
<div>
<input type="button" value="全选" id="alltrue">
<input type="button" value="反选" id="opposite">
<input type="checkbox" id="allcheck" disabled="disabled">
</div>
<ul id="inp">
<li><input type="checkbox" id="1"></li>
<li><input type="checkbox" id="2"></li>
<li><input type="checkbox" id="3"></li>
<li><input type="checkbox" id="4"></li>
<li><input type="checkbox" id="5"></li>
<li><input type="checkbox" id="6"></li>
<li><input type="checkbox" id="7"></li>
<li><input type="checkbox" id="8"></li>
<li><input type="checkbox" id="9"></li>
<li><input type="checkbox" id="10"></li>
</ul>
<script>
var alltrue = document.getElementById('alltrue');
var opposite = document.getElementById('opposite');
var allcheck = document.getElementById('allcheck');
var inp_list = document.getElementById('inp');
var ckboxes = inp_list.getElementsByTagName('input');
alltrue.onclick = function(){
var i;
for(i=0;i<ckboxes.length;i++){
ckboxes[i].checked = true;
}
allcheck.checked = true;
}
opposite.onclick = function(){
var i;
for(i=0;i<ckboxes.length;i++){
if(ckboxes[i].checked){
ckboxes[i].checked = false;
}else{
ckboxes[i].checked = true;
}
}
allcheck.checked = judge();
}
//判断ul中所有的复选框有没有被全选
function judge(){
var i;
for(i=0;i<ckboxes.length;i++){
if(!ckboxes[i].checked){
return false;
}
}
return true;
}
//给每一个复选框绑定事件
var i;
for(i=0;i<ckboxes.length;i++){
ckboxes[i].onclick = function(){
allcheck.checked = judge();
}
}
</script>
</body>
</html>
“`