当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js中全选和全不选

js中全选和全不选

2020年07月28日  | 移动技术网IT编程  | 我要评论
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作复选框</title>
</head>
<body>

<input type="checkbox" id="quan"> 全选<br>
<input type="checkbox" name="aihao">游戏<br>
<input type="checkbox" name="aihao">睡觉<br>
</body>
</html>
<script type="text/javascript">

    window.onload=function () {

        var firstChecbox = document.getElementById("quan");
        var aihao=document.getElementsByName("aihao");
        //完成全选和全不选
        //当单击全选时使下方的checkbox中的checked属性为true
        firstChecbox.onclick=function () {
            //遍历下方的checkbox
            //使每一个复选框的属性中的checked和全选的属性保持一致即可实现(不完善)
            for (let i = 0; i <aihao.length ; i++) {
                aihao[i].checked=firstChecbox.checked;
            }
        }
        //如果选中的数量和爱好的总数量一致的就把全选给选中,否则不全选
        //为每一个aihao绑定单击事件
        var  all=aihao.length;
        for (let i = 0; i < aihao.length; i++) {
            //绑定单击事件
            aihao[i].onclick=function () {
            //定义选中的数量
                var checkedCount=0;
                for (let i = 0; i < aihao.length; i++) {
                //如果爱好选中就把选中的数量+1;
                    if (aihao[i].checked){
                        checkedCount++;
                    }
                    //如果选中的数量和总数相当就把全选给勾选
                    if (checkedCount==all){
                        firstChecbox.checked=true
                    }
                    else{
                        firstChecbox.checked=false;
                    }
                }
            }

        }
    }

</script>

本文地址:https://blog.csdn.net/csdn_cai/article/details/107589697

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网