题解 | #全选#

全选

https://www.nowcoder.com/practice/84b89f326e3c4e96bacb63296e84623a

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
        <style>
            ul {
                list-style: none;
            }
        </style>
    <body>
        <ul>
            <li>全选<input type='checkbox' id='all'></li>
            <li>Java<input type='checkbox' class='item'></li>
            <li>javaScript<input type='checkbox' class='item'></li>
            <li>C++<input type='checkbox' class='item'></li>
            <li>python<input type='checkbox' class='item'></li>
            <li>.net<input type='checkbox' class='item'></li>
        </ul>

        <script>
            // 补全代码
            var all = document.querySelector('#all');
            var options = Array.from(document.querySelectorAll('.item'));
            all.onchange = () => {
                options.forEach(i => i.checked = all.checked)
            }
            options.forEach( item =>{
                item.onchange = function() {
                    all.checked = options.every(x => x.checked)
                }
            })
        </script>
    </body>
</html>

注意:类数组对象一定要通过Array.from()将其转化为数组才能用数组的every方法。

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务