jQuery制作复选框

2023-05-06,

                                                           

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="jQuery/jquery.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div>
            <input type="checkbox" name = "check"><br>
            <input type="checkbox" name = "check"><br>
            <input type="checkbox" name = "check"><br><br>
            <input type="checkbox" id="checkAll">全选

        </div>
        <script type="text/javascript">
            //  方法1 有瑕疵需要个变量
            $(function(){   //获取所有input ,点击触发函数
                $("input[name='check']").click(function(){
                    // 定义变量
                    var i = 0;
                    // 遍历name=check的按钮  也就是除了全选按钮之外的,名字可以随便写
                    $("input[name='check']").each(function(){
                        // 判断,该按钮checked的值为true
                        if($(this).prop("checked")){
                            // 变量+1
                            i++;
                        }
                        // 判断 变量值==复选框数量时
                        if(i == $("input[name='check']").length){
                            // 将全选按钮的checked的值设为true
                            $("#checkAll").prop("checked",true);
                        }else{
                            // 否则设为false
                            $("#checkAll").prop("checked",false)
                        }
                    })
                })

                //  点击全选框   
                $("#checkAll").click(function(){
                    //  让type为checkbox的都添加checked
                    $("input[name='check']").prop("checked",this.checked);
                })
            })

            //  方法2 不需要变量

            $(function(){   //获取所有input ,点击触发函数
                $("input[name='check']").click(function(){
                    // 定义变量
                    var i = 0;
                    // 遍历name=check的按钮  也就是除了全选按钮之外的,名字可以随便写
                    $("input[name='check']").each(function(){
                        // 判断,该按钮checked的值为true
                        if($("[name='check']:checked").length == $("input[name='check']").length){
                            $("#checkAll").prop("checked",true);
                        }else{
                            $("#checkAll").prop("checked",false)
                        }
                    })
                })

                //  点击全选框   
                $("#checkAll").click(function(){
                    //  让type为checkbox的都添加checked
                    $("input[name='check']").prop("checked",this.checked);
                })
            })

        </script>
    </body>
</html>

《jQuery制作复选框.doc》

下载本文的Word格式文档,以方便收藏与打印。