js实现全选全不选反选

时间:2022-03-29 09:06:56
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>全选全不选反选</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}


body{
margin: 30px 20px;
font-size: 16px;
color: #666;
}


div{margin-bottom: 20px;}
label{margin-right: 15px;}

li{
list-style: none;
height: 25px;
line-height: 25px;
}

</style>
</head>
<body>
<div>
<label for="">全选<input type="checkbox" id="checkAll" /></label>
<label for="">全不选<input type="checkbox" id="checkNo" /></label>
<label for="">反选<input type="checkbox" id="checkReserve"/></label>
</div>
<ul>
<li><input type="checkbox" name="item"/>1.....</li>
<li><input type="checkbox" name="item"/>2.....</li>
<li><input type="checkbox" name="item"/>3.....</li>
<li><input type="checkbox" name="item"/>4.....</li>
<li><input type="checkbox" name="item"/>5.....</li>
<li><input type="checkbox" name="item"/>6.....</li>
</ul>
</body>
<script type="text/javascript">
window.onload = function(){
var oItems = document.getElementsByName('item');
var oCheckAll = document.getElementById('checkAll');
var oCheckNo = document.getElementById('checkNo');
var oCheckReserve = document.getElementById('checkReserve');

//全选
oCheckAll.onclick = function(){
for(var i=0;i<oItems.length;i++){
oItems[i].checked=true;
}
};

//全不选
oCheckNo.onclick = function(){
for(var i=0;i<oItems.length;i++){
oItems[i].checked=false;
}
};

//反选
oCheckReserve.onclick = function(){
for(var i=0;i<oItems.length;i++){
if(oItems[i].checked==true){
oItems[i].checked=false;
}
else{
oItems[i].checked=true;
}
}
}
}
</script>
</html>