<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="../jquery-3.0.0.min.js"></script>
    <style>
    </style>
</head>

<body>
    <div class="wrap">
            <table>
                    <tr>
                        <th></th>
                        <th>乐器</th>
                        <th>种类</th>
                    </tr>
                    <tr>
                        <td><input type="checkbox" name="" id=""></td>
                        <td>钢琴</td>
                        <td>打击</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" name="" id=""></td>
                        <td>吉他</td>
                        <td>弹拨</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" name="" id=""></td>
                        <td>提琴</td>
                        <td>弦乐</td>
                    </tr>
                </table>
                Select all  <input type="checkbox" name="" id="chosseall">
    </div>
    <script>
        $(function(){
            $('table input').click(function(){
                var length1=$('table input').length;
                var length2=$('table input:checked').length;
                if(length1==length2){
                    $("#chosseall").prop('indeterminate',false);
                    $("#chosseall").prop('checked',true) 
                }
                else{
                    $("#chosseall").prop('indeterminate',true);
                }
            })
            $("#chosseall").click(function(){
                    $("input").prop("checked",$(this).prop('checked'))

            })            
            })

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

上述代码实现使用jQuery实现了表格全选框的功能

对于table中input的点击事件,每次要判断是否选择框选满了,如果没选满就将 checkbox 的indeterminate属性设置为true,如果选满了就将checked属性设置为true

indeterminate属性会在为true的时候 会覆盖checked为true 时的状态,所以在设置为indeterminate="true"之前先将其设置为false

否则就会出现选完了虽然 checked为true但是显示的还是indeterminate="true"的状态

 posted on 2018-09-13 14:08  Muic  阅读(263)  评论(0编辑  收藏  举报