JS反选全选案例

在这里插入图片描述

<!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>
        // 实现全选 单选功能
        // 得到单项的dom对象
        const list = Array.from(document.getElementsByClassName('item'));
        // 得到全选框的dom对象
        const all = document.getElementById('all')
        // console.log(list);

        // 全选
        function allChange() {
            list.forEach((item) => {
                item.checked = all.checked
            })
        }

        all.onchange = allChange

        // 单个选项框决定全选状态
        list.forEach(element => {
            element.onchange = () => {
                // 设置一个空值全选框的默认值
                var isDisplay = true
                // 如果有单选框为flase 全选框就为false 否则为true
                list.forEach(value => {
                    if (value.checked === false) {
                        isDisplay = false
                    }
                })
                // console.log(isDisplay);
                // 事件改变 最后赋值全选状态
                all.checked = isDisplay;
            }
        });

    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值