关于用jQuery实现的checkbox全选和反选功能

时间:2022-01-24 03:15:06



    用jQuery实现了checkbox的全选和反选功能,代码如下:


  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>复选框全选反选</title>
    <style type="text/css">
        body,dl,dt,dd,p{margin:0;padding:0;}
        body{font-family:Tahoma;font-size:12px;}
        label,input,a{vertical-align:middle;}
        label{padding:0 10px 0 5px;}
        a{color:#09f;text-decoration:none;}
        a:hover{color:red;}
        dl{width:120px;margin:10px auto;padding:10px 5px;border:1px solid #666;border-radius:5px;background:#fafafa;}
        dt{padding-bottom:10px;border-bottom:1px solid #666;}
        dt label{font-weight:700;}
        p{margin-top:10px;}

    </style>
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#checkAll").click(function(){
                if($(this).is(":checked"))
                {
                  $(this).next("label").html("不全选");
                    $("input:checkbox").not($(this)).attr("checked","checked");
                }
                else{
                    $(this).next("label").html("全选");
                    $("input:checkbox").not($(this)).removeAttr("checked");

                }

            })



            $("#back").click(function(){
                var t=$("dd input:checkbox:checked");

                $("dd input:checkbox").not(t).attr("checked","checked");
                t.removeAttr("checked");
                check();
            })
            $("dd input:checkbox").click(function(){
                check();


            });
            function check(){
                var t=$("dd input:checkbox:checked");
                var m=$("dd input:checkbox");
                if(t.length == m.length)
                    $("#checkAll").attr("checked","checked");
                else
                    $("#checkAll").removeAttr("checked");
            }
        })

    </script>
</head>
<body>
<dl>
    <dt><input type="checkbox" id="checkAll" /><label>全选</label><a  id="back">反选</a></dt>
    <dd>
        <p><input type="checkbox" name="item" /><label>选项(一)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(二)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(三)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(四)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(五)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(六)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(七)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(八)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(九)</label></p>
        <p><input type="checkbox" name="item" /><label>选项(十)</label></p>
    </dd>
</dl>
<center>1、切换全选/全不选文字;2、根据选中个数更新全选框状态;</center>

</body>
</html>