1.先写一个html页面,里面写一个全选按钮和几个复选框,实现下面2个要求
(1)点击全选按钮选中时,所有的复选框选中.
(2)点击全选按钮取消选中时,所有复选框取消选中。
<input type="checkbox" id="quanxuan" />全选<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br />
2.js处理代码
$("#quanxuan").click(function(){//给全选按钮加上点击事件 var xz = $(this).prop("checked");//判断全选按钮的选中状态 var ck = $(".qx").prop("checked",xz); //让class名为qx的选项的选中状态和全选按钮的选中状态一致。 })
以上代码完全可以完美的实现要求的2个功能。这里需要注意的是不能使用下面的方法做全选按钮,因为下面的方法有严重的不足之处。
1.html页面
<input type="checkbox" onclick="quanxuan(this)" />全选<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br /> <input type="checkbox" class="qx" />aa<br />
2.处理页面
<script type="text/javascript"> function quanxuan(a) { //找到下面所有的复选框 var ck =document.getElementsByClassName("qx"); //遍历所有复选框,设置选中状态。 for(var i=0;i<ck.length;i++) { if(a.checked)//判断全选按钮的状态是不是选中的 { ck[i].setAttribute("checked","checked");//如果是选中的,就让所有的状态为选中。 } else { ck[i].removeAttribute("checked");//如果不是选中的,就移除所有的状态是checked的选项。 } } } </script>