全选 反选

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <input type="checkbox" id="all">全选<br>
    </div>


    <div id="tb">
        <input type="checkbox">1 <br>
        <input type="checkbox">2 <br>
        <input type="checkbox">3 <br>
        <input type="checkbox">4 <br>
    </div>
    <div>
        <input type="button" value="反选" id="btn">
    </div>
    </table>


    <script>
        var all = document.getElementById("all");
        var tb = document.getElementById("tb");
        var tb_inputs = tb.getElementsByTagName("input");
        var btn = document.getElementById("btn");


        //全选
        all.onclick = function () {
            for (var i = 0; i < tb_inputs.length; i++) {
                tb_inputs[i].checked = all.checked;
            }
        };

        //单独选择子选项过程
        for (var i = 0; i < tb_inputs.length; i++) {
            tb_inputs[i].onclick = function () {
                // 假设初始状态每个子选项都是被选中的
                allChecked();
            }
        }

        //反选
        btn.onclick = function () {
            for (var i = 0; i < tb_inputs.length; i++) {
                tb_inputs[i].checked = !tb_inputs[i].checked;
            }
            // 全选控制
            allChecked();

        }

        function allChecked(){
            // 假设初始状态每个子选项都是被选中的
            var isAllChecked = true;

            for (var j = 0; j < tb_inputs.length; j++) {
                if (tb_inputs[j].checked == false) {
                    isAllChecked = false;
                    break;
                }
            }

            all.checked = isAllChecked;
        }
    </script>
</body>

</html>
posted @ 2021-08-13 11:26  charonmomo  阅读(44)  评论(0编辑  收藏  举报