prop方法实现全选效果

今天来写一下关于全选的效果,这里先写一个表格,大概写完效果图如下:

我想我不说明都应该知道点击最上面的checkbox全部选中,再次点击全部取消,然后点击下面的几个全选的不被选中,而下面的全部都点击之后,全选的自然被选中,这就是要实现的效果。直接来看代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *{ margin:0; padding:0;}
    dl{list-style: none;}
    .box{ width:400px; height:40px; margin:0 auto;}
    .box dl{ list-style:none;overflow: hidden;border:1px solid #e5e5e5;}
    .box dl dt{background: #ff7e7e;font-size:16px;color:#fff;}
    .box dl dt,.box dl dd{border-bottom:1px solid #e5e5e5;}
    .box dl dd:last-child{border:none;}
    input{margin:10px 20px;}
    span{padding:10px 20px;display:inline-block;width:60px;text-align: center}
</style>
<body>
<div class="box">
    <dl>
        <dt>
            <input type="checkbox" id="cktit"/>
            <span>标题</span>
            <span>标题1</span>
            <span>标题2</span>
        </dt>
        <dd>
            <input type="checkbox"/>
            <span>内容</span>
            <span>内容</span>
            <span>内容</span>
        </dd>
        <dd>
            <input type="checkbox"/>
            <span>内容</span>
            <span>内容</span>
            <span>内容</span>
        </dd>
        <dd>
            <input type="checkbox"/>
            <span>内容</span>
            <span>内容</span>
            <span>内容</span>
        </dd>
        <dd>
            <input type="checkbox"/>
            <span>内容</span>
            <span>内容</span>
            <span>内容</span>
        </dd>
    </dl>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
    $(function(){
        $("#cktit").click(function(){
            $("dl dd input").prop("checked",$(this).prop("checked"));
        });
        $("dl dd input").click(function(){
            var inputLength = $("dl dd input:checked").length;//选中的input的长度
            var allLength = $("dl dd input").length; //所有input的长度
            if(inputLength == allLength){
                $("#cktit").prop("checked",true);
            }else{
                $("#cktit").prop("checked",false);
            }
        })
    })
</script>

</body>
</html>

这样完成了一个表格的全选效果了。

有一个问题需要注意:

用attr这个方法来更改或读取checkbox的checked属性也是可以的,但是需要说明的是,若是引用jquary1.6版本之前是可以实现的,而之后的版本就只能点击一次再次点击就失效了,必须要用到prop方法了。因为以上案例中引用的是jquery-1.11.3的版本,所以我用的是prop方法。

原文地址:https://www.cnblogs.com/web001/p/8379352.html