摘要:<!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:循環(huán)操作在此處的運用