海阔天空

当前时间为:
欢迎大家来到海阔天空https://www.9713job.com,广告合作以及淘宝商家推广请微信联系15357240395

2020javaweb教程之jQuery全选、反选、全不选

未分类
2020-11-21 16:36:20
1822677238@qq.com

手机扫码查看

2020javaweb教程之jQuery全选、反选、全不选

2020javaweb教程之jQuery全选、反选、全不选

<table>
    <tr>
        <td><input type="checkbox" id="allbox">全选</td>
        <td><input type="checkbox" id="allnobox">全不选</td>
        <td><input type="checkbox" id="fanbox">反选</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="box"></td>
        <td></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="box"></td>
        <td></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="box"></td>
        <td></td>
    </tr>
</table>
<script>
    $(function(){
        var allbox=$("#allbox");//获取全选
        var boxs=$(".box");//获取所有复选框
        //反选
        var fx=$("#fanbox");
        fx.click(function(){
            for(var i=0;i<boxs.length;i++){
                var r=$(boxs[i]).prop("checked");
                if(r==true){
                    $(boxs[i]).prop("checked",false)
                }else $(boxs[i]).prop("checked",true)
            }
        })
        //全选
        allbox.click(function(){
            var result=$(this).prop("checked");
            if(result==true){
                boxs.prop("checked",true);
            }else boxs.prop("checked",false);
        })
        //全不选
        var allnobox=$("#allnobox");
        allnobox.click(function(){
            var lists=$("input[type='checkbox']");
            for(var i=0;i<lists.length;i++){
                var r=$(lists[i]).prop("checked");
                if(r==true) {
                    $(lists[i]).prop("checked",false)
                }
            }
        })
        //反向全选 2.利用 each迭代
        boxs.click(function(){
            var c=0;
            $.each(boxs,function(i,v){
                if($(boxs[i]).prop("checked")==true){
                    c++;
                    if(c==boxs.length){
                        allbox.prop("checked",true);
                    } 
                    else allbox.prop("checked",false);
                }
            })
        })
        //反向全选 1.利用for循环
        boxs.click(function(){
            var c=0;//计数器
            for(var i=0;i<boxs.length;i++){
                //如果多个复选框都为true
                var r=$(boxs[i]).prop("checked");
                if(r==true){
                    c++;//计数器++
                    //如果计数器等于多个复选框,将全选框设置true
                    if(c==boxs.length) {
                        allbox.prop("checked",true);
                    }
                    //否则全选为false
                    else allbox.prop("checked",false);
                }
            }
        })
    })
</script>





发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注