全选的完成代码及总结理解

Original 2019-05-06 14:41:35 182
abstract:<!doctype html><html><head><meta charset="utf-8"><title>全选或反选</title><style type="text/css"> .box{width:150px;height: auto inherit; b

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>全选或反选</title>

<style type="text/css">
 .box{width:150px;height: auto inherit; border:solid #ccc 1px; border-radius:5px;margin-top: 5px;padding: 0px,10px;margin: 20px auto;}
 .box1{width:120px; border-bottom: 1px solid #ccc;padding-bottom: 10px;margin-top: 10px}
 .box2 input{margin: 8px}
 
 
</style>
</head>
 

 <script type="text/javascript">

//复选框的全选
function checkAll(){
    var chec = document.getElementById("checkall").checked;//复选框是否选中,选中为true,没选中则为false
    var likes = document.getElementsByName("like");//通过name获得所有指定name的对象,结果集为数组对象
for(var i=0;i<likes.length;i++){
likes[i].checked = chec;//将全选框获得的值赋给需要选择的框

}
//复选框的反选
function checkOthers(){
var likes = document.getElementsByName("like");//通过name获得所有指定name的对象,结果集为数组对象
var countchecked = 0;//本次操作一共选中了多少个
var count = 0;//本次操作没选中多少个
for(var i=0;i<likes.length;i++){
if(likes[i].checked==true){
likes[i].checked=false;
count++;
}else{
likes[i].checked=true;
countchecked++;
}
}
if(countchecked == likes.length)
{
document.getElementById("checkall").checked=true;
}else{
document.getElementById("checkall").checked=false;
}
}
  </script>
 </head>
 <body>

<div class="box" align="center" >
 <div class="box1">
<input type="checkbox" value="all" name="all" id="checkall" onclick="checkAll()"/>全选
<input type="checkbox" value="other" name="other" id="checkOther" onclick="checkOthers()"/>反选
  </div>
  <br/>
 <div class="box2">
<input type="checkbox" value="选项1" name="like" />选项1<br>
<input type="checkbox" value="选项2" name="like" />选项2<br>
<input type="checkbox" value="选项3" name="like" />选项3<br>
<input type="checkbox" value="选项4" name="like" />选项4<br>
</div>
 </div>

</body>
</html>

总结:

关键点1:获取到相关复选框

关键点2:对获取到的复选框进行操作

关键点3:循环操作在此处的运用

Release Notes

Popular Entries