菜单列表的全选功能实现

Original 2019-04-25 19:54:40 253
abstract:<!DOCTYPE html> <html lang="zh-cn"> <head>    <meta charset="UTF-8">    <title>全选</title>  &n
<!DOCTYPE html>
<html lang="zh-cn">
<head>
   <meta charset="UTF-8">
   <title>全选</title>

   <style type="text/css">
 .box{
         width: 120px;
 height: 230px;
 border: 1px solid gray;
 border-radius: 5px;
 padding: 5px 10px;
 margin: 20px auto;
 }
      .box input{
         margin: 8px;
 }
   </style>

   <script type="application/javascript">
 function cecal() {
         let cecal,item;
 cecal = document.getElementById('cecal')//获取全选
 item = document.getElementsByName('item[]')//获取下面单选框

 // for 循环
 // for (let i = 0; i < item.length; i++) {//获取到长度6之后,开始循环,变量是从0开始
 //     if (cecal.checked){//判断全选框是否被选中
 //        item[i].checked = true//当全选被选中的时候,勾选下面的单选框
 //     } else {
         //        item[i].checked = false//反之
 //     }
         // }

         // while 循环
 let x = 0;
 while (x < item.length) {
            if (cecal.checked){
               item[x].checked = true//当全选被选中的时候,勾选下面的单选框
 } else {
               item[x].checked = false//反之

 }
            x++;


 }


      }

   </script>


</head>
<body>

   <div class="box">
      <div>
         <input type="checkbox" id="cecal" onclick="cecal()"><label for="cecal">全选</label>
      </div>
      <hr>
      <input type="checkbox" name="item[]" id="select1" value="select1"><label for="select1">选择1</label><br>
      <input type="checkbox" name="item[]" id="select2" value="select1"><label for="select2">选择2</label><br>
      <input type="checkbox" name="item[]" id="select3" value="select1"><label for="select3">选择3</label><br>
      <input type="checkbox" name="item[]" id="select4" value="select1"><label for="select4">选择4</label><br>
      <input type="checkbox" name="item[]" id="select5" value="select1"><label for="select5">选择5</label><br>
      <input type="checkbox" name="item[]" id="select6" value="select1"><label for="select6">选择6</label><br>

   </div>
</body>
</html>

实现这个功能主要用到鼠标点击处理事件,onclick。

利用javaScript实现

首先获取到全选的标签 和数组item[]标签

然后利用循环来判断,获取到item[]数组的长度(数组个数)

依次对下面单选框进行勾选或者取消勾选。

Correcting teacher:查无此人Correction time:2019-04-26 13:31:23
Teacher's summary:完成的不错。相信你现在对js有一定的了解了,继续加油。

Release Notes

Popular Entries