HTML结构:
<!doctype html>
<html><head><meta charset="utf-8"><title>无标题文档</title></head><body>
<input type="checkbox" id="selectall"/>全选<div id="div"> <input type="checkbox" />A<br /> <input type="checkbox" />B<br /> <input type="checkbox" />C<br /> <input type="checkbox" />D<br /> <input type="checkbox" />E<br /> <input type="checkbox" />F<br /></div></body></html>CSS样式:
.div1{width:300px; height:100px; border:1px solid #09F;}
label{display:block; margin-bottom:20px;}原生Javascript代码:
<script>
var oSelectall = document.getElementById("selectall");var aCheck = document.getElementById("div").getElementsByTagName("input");oSelectall.onclick = function(){ for(var i=0; i<aCheck.length;i++){ f(this.checked==true){ aCheck[i].checked = true; }else{ aCheck[i].checked = false; } } }var all_length = aCheck.length;var add_all = 0;for(var i=0; i<aCheck.length;i++){ aCheck[i].onclick = function(){ if(this.checked==true){ add_all++; }else{ add_all--; } if(add_all == all_length){ oSelectall.checked = true; }else{ oSelectall.checked = false; } }}</script>jQuery源码:
<script src="js/jquery-1.9.1.min.js"></script>
<script>$(function(){ $('#selectall').click(function(){ if(this.checked==true){ $('#div').find('input').prop('checked',true); }else{ $('#div').find('input').prop('checked',false); } }); var input_length = 0; $('#div').find('input').click(function(){ if(this.checked){ input_length++; }else{ input_length--; } if(input_length == $('#div').find('input').length){ $('#selectall').prop('checked',true); }else{ $('#selectall').prop('checked',false); } });});</script>