全选与反选

全选与反选

<body>
    <div class="box">
        <table width=300px cellspacing=100px>
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" class="head">
                    </th>
                    <th>1</th>
                    <th>2</th>
                </tr>
            </thead>
            <tbody class="ooo">
                <tr>
                    <td><input type="checkbox"></td>
                    <td>3</td>
                    <td>4</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>3</td>
                    <td>4</td>
                </tr>
                <tr>
                    <td><input type="checkbox"></td>
                    <td>3</td>
                    <td>4</td>
                </tr>
            </tbody>
        </table>
    </div>
    ```
    ```javascript
    <script>
        var head = document.querySelector('.head');
        var hands = document.querySelector('.ooo').querySelectorAll('input');
        console.log(head);
        console.log(hands);
        //上面的决定下面的
        head.onclick = function() {
                for (var i = 0; i < hands.length; i++) {
                    hands[i].checked = head.checked;
                }
            }
            //下面的决定上面的  只要有一个未被选中,则全选按钮不会选中
        for (var i = 0; i < hands.length; i++) {
            hands[i].onclick = function() {
            //引入flag,来判定选中与否的状态
                var flag = true;
                for (var i = 0; i < hands.length; i++) {
                    if (!hands[i].checked) {
                        flag = false;
                        break;
                    }
                }
                head.checked = flag;
            }

        }
    </script>
</body>
发布了6 篇原创文章 · 获赞 1 · 访问量 186

猜你喜欢

转载自blog.csdn.net/weixin_45158253/article/details/100192314