date1101全选效果

34 阅读1分钟
<!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>
    全选:<input type="checkbox" class="all">
    <hr>
    单选:<input type="checkbox" class="other"><br>
    单选:<input type="checkbox" class="other"><br>
    单选:<input type="checkbox" class="other"><br>
    单选:<input type="checkbox" class="other"><br>
    单选:<input type="checkbox" class="other"><br>

    <script>
        var oAll = document.querySelector('.all');
        var oOthers = [...document.querySelectorAll('.other')];
        console.log(oOthers);

        // 功能1
        // 原始版
        oAll.onclick = function () {
            if (oAll.checked === true) {
                oOthers.forEach(function (value) {
                    value.checked = true;
                })

            } else {
                oOthers.forEach(function (value) {
                    value.checked = false;
                })
            }
        }

        //优化版
        oAll.onclick = function(){
            oOthers.forEach(function(value){
                value.checked = oAll.checked;
            })
        }

        // 功能2
        // 循环遍历里面的没一个数值
        oOthers.forEach(function(value){

            // console.log(value);

            // 给每一个input添加点击事件
            value.onclick = function(){

                // 如果全部选中
                // 就把这个true赋值给全选按钮
                oAll.checked = oOthers.every(function(value){
                    console.log(oAll.checked);
                    
                    // 返回布尔值
                    return value.checked;
                })
            }
        })
        

    </script>
</body>

</html>