jQuery 表格全选反选

473 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    .wrap {
      width: 300px;
      margin: 100px auto 0;
    }
    table {
      border-collapse: collapse;
      border-spacing: 0;
      border: 1px solid #c0c0c0;
    }
    th, td {
      border: 1px solid #d0d0d0;
      color: #404060;
      padding: 10px;
    }
    th {
      background-color: #09c;
      font: bold 16px "微软雅黑";
      color: #fff;
    }
    td {
      font: 14px "微软雅黑";
    }
    tbody tr {
      background-color: #f0f0f0;
    }
    tbody tr:hover {
      cursor: pointer;
      background-color: #fafafa;
    }
  </style>
  <script src="jquery-3.4.1.js"></script>
  <script>
    $(function () {
      // 全选按钮点击
      $('#select_all').click(function () {
        // 直接让下面所有按钮跟上面按钮的属性值一样
        $('#tb_content input:checkbox').prop('checked', $(this).prop('checked'))
      });

      // 下面所有的选择按钮
      $('#tb_content input:checkbox').click(function () {
        // 判断只有所有都选中,全选按钮才会被选中
        var boxs = $('#tb_content input:checkbox');
        // 获得带 checked 属性的 box
        var selectBoxs = $('#tb_content').find(':checkbox:checked');
        // var selectBoxs = $('#tb_content input:checked');
        if (boxs.length === selectBoxs.length) {
          $('#select_all').prop('checked', true);
        }else{
          $('#select_all').prop('checked', false);
        }
      })
    })
  </script>
</head>
<body>
  <div class="wrap">
    <table>
      <thead>
        <tr>
          <th>
            <input type="checkbox" id="select_all" />
          </th>
          <th>课程名称</th>
          <th>所属学院</th>
        </tr>
      </thead>
      <tbody id="tb_content">
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>JavaScript</td>
          <td>前端与移动开发学院</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>css</td>
          <td>前端与移动开发学院</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>html</td>
          <td>前端与移动开发学院</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>jQuery</td>
          <td>前端与移动开发学院</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>
  • demo 效果: