js全选和全不选 js实现全选和全不选功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js全选和全不选 js实现全选和全不选功能

哀愁   2021-01-29 我要评论

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>操作复选框</title>
</head>
<body>

<input type="checkbox" id="quan"> 全选<br>
<input type="checkbox" name="aihao">游戏<br>
<input type="checkbox" name="aihao">睡觉<br>
</body>
</html>
<script type="text/javascript">

 window.onload=function () {

  var firstChecbox = document.getElementById("quan");
  var aihao=document.getElementsByName("aihao");
  //完成全选和全不选
  //当单击全选时使下方的checkbox中的checked属性为true
  firstChecbox.onclick=function () {
   //遍历下方的checkbox
   //使每一个复选框的属性中的checked和全选的属性保持一致即可实现(不完善)
   for (let i = 0; i <aihao.length ; i++) {
    aihao[i].checked=firstChecbox.checked;
   }
  }
  //如果选中的数量和爱好的总数量一致的就把全选给选中,否则不全选
  //为每一个aihao绑定单击事件
  var all=aihao.length;
  for (let i = 0; i < aihao.length; i++) {
   //绑定单击事件
   aihao[i].onclick=function () {
   //定义选中的数量
    var checkedCount=0;
    for (let i = 0; i < aihao.length; i++) {
    //如果爱好选中就把选中的数量+1;
     if (aihao[i].checked){
      checkedCount++;
     }
     //如果选中的数量和总数相当就把全选给勾选
     if (checkedCount==all){
      firstChecbox.checked=true
     }
     else{
      firstChecbox.checked=false;
     }
    }
   }

  }
 }

</script>

更多关于复选框的文章请点击专题:javascript复选框操作汇总jquery复选框操作汇总

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们