• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ellaha
博客园    首页    新随笔    联系   管理    订阅  订阅
复选框全选和反选
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
            border: 1px solid #000;
            width: 300px;
            height: 400px;
            text-align: center;
            border-spacing: 0;
            background: url(img/2.jpg) no-repeat;
            background-size: 300px 400px;
        }
        th,
        td {
           border: 1px solid #000;
        }

    </style>
    <script>
    window.onload = function () {
        // 1,全选
        var j_tb = document.getElementById('j_tb');
        var inputs = j_tb.getElementsByTagName('input');

        // 1.1 获取父checkbox 注册点击事件
        var allSel = document.getElementById('allSel');
        allSel.onclick = function () {
              for (var i=0; i < inputs.length; i++) {
                  input = inputs[i];
                  if (input.type === 'checkbox') {
                      // 1.2 子父checkbox状态保持一致
                      input.checked = allSel.checked;
                  }
              }
        }
        // 2, 当点击子checkbox 如果所有的子checkbox都被选中了让父的checkbox也选中
        //如果有一个子checkbox没被选中 父的checkbox也不被选中


        // 3 反选
        // 给反选按钮注册点击事件
        var btn = document.getElementById('btn');
        btn.onclick = function () {
            // 找到所有的子checkbox 让其反选
            for (var i=0; i < inputs.length; i++) {
                var input = inputs[i];
                if (input.type !== 'checkbox') {
                    continue;
                }
                // 让checkbox反选
                input.checked = !input.checked;
            }
        }
    }
    </script>
</head>
<body>
<div>
    <table class="facility">
        <thead>
            <tr>
                <th>
                    <input type="checkbox" id="allSel">
                </th>
                <th>设备</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody id="j_tb">
            <tr>
                <td><input type="checkbox"></td>
                <td>苹果8</td>
                <td>8000</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>苹果7</td>
                <td>7000</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>苹果6</td>
                <td>6000</td>
            </tr>
        </tbody>
    </table>
    <input type="checkbox" value="反选" id="btn">
</div>
</body>
</html>

 

posted on 2021-03-16 15:50  ellaha  阅读(109)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3