欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jquery实现全选功能

程序员文章站 2022-07-13 23:02:09
...

<!--HTML部分:-->

<ul>
    <li><input type="checkbox" class="chk" id="checkAll"/><label for="checkAll">全选</label></li>
    <li><input type="checkbox" class="chk chk01"/>1</li>
    <li><input type="checkbox" class="chk chk01"/>2</li>
    <li><input type="checkbox" class="chk chk01"/>3</li>
    <li><input type="checkbox" class="chk chk01"/>4</li>
    <li><input type="checkbox" class="chk chk01"/>5</li>
</ul>

<!--JS部分:-->

$(document).on("click","#checkAll",function(){
   $(".chk01").prop("checked",$(this).prop("checked"))//多选框的状态与全选框状态保持一致
})
                    
$(".chk01").each(function(){
    $(this).click(function(){
        if(!$(this).prop("checked")){//多选框有一个未选中 全选变为未选中状态
            $("#checkAll").prop("checked",false)
        }else if($(this).prop("checked")){
            $(".chk01").each(function(index,ele){
                if($(this).prop("checked")){
                    if(index == $(".chk01").length - 1){
                        $("#checkAll").prop("checked",true)//多选框全部选中 全选变为选中状态
                    }
                    return true//each()跳过本次循环
                }else{
                    return false//each()跳出循环
                } 
            })
        }
    })
})