<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复选</title>
</head>
<body>
<input type="button" value="全选" id='both'>
<input type="button" value="反选" id='inverse'>
<input type="button" value="不选" id='none'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
<input type="checkbox" name='one'>
</body>
<script>
//全选
var both = document.getElementById('both');
var one = document.getElementsByName('one'); /* 获取复选框下的name */
both.onclick = function(){
for(var i=0; i<one.length; i++){ /* length只能用在群组里 不能给单个标签用 */
if(one[i].checked==false){
one[i].checked=true;
}
}
}
//反选
var inverse = document.getElementById('inverse');
inverse.onclick =function(){
for(var i = 0 ; i < one.length ; i++){
if(one[i].checked == true){
one[i].checked = false ;
}else{
one[i].checked = true ;
}
}
}
//不选
var none = document.getElementById('none');
none.onclick = function(){
for(i = 0 ; i < one.length ; i++){
if(one[i].checked == true){
one[i].checked = false ;
}
}
}
</script>
</html>
更新一波:更简便的方法
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>反选效果</title>
</head>
<body>
<div id="btns">
<input type="button" value='全选'>
<input type="button" value='反选'>
<input type="button" value='不选'>
</div>
<div id='box'>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
</body>
<script>
var btns = document.getElementById('btns');
var btn_inps = btns.getElementsByTagName('input');
var box = document.getElementById('box');
var box_inps = box.getElementsByTagName('input');
/* //全选
btn_inps[0].onclick = function(){
for(i = 0 ; i < box_inps.length ; i++){
// console.log(box_inps[i]);
box_inps[i].checked = true;
}
}
*/
//反选
btn_inps[1].onclick = function(){
for(i = 0 ; i < box_inps.length ; i++){
if(box_inps.checked == true){
box_inps[i].checked = false;
}else{
box_inps[i].checked = true;
}
}
}
/* //不选
btn_inps[2].onclick = function(){
for(i = 0 ; i < box_inps.length ; i++){
box_inps[i].checked = false;
}
}
*/
btn_inps[0].onclick = function(){
show(true);
}
btn_inps[2].onclick = function(){
show(false);
}
function show(bool){
for(var i = 0 ; i < box_inps.length ; i++){
box_inps[i].checked = bool;
}
}
show();
</script>
</html>
/* 注: 从我的编辑器里复制过来的 Tab键用的格式可能有点不太对,是需要稍微调整一下的 */