用 jQuery 实现全选/反选功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="checkbox" id="ch_all">全选<button>反选</button>
    <ul>
        <li> <input type="checkbox" class="j-chbox">张三</li>
        <li> <input type="checkbox" class="j-chbox">李四</li>
        <li> <input type="checkbox" class="j-chbox">麻子</li>
    </ul>
    <script src="jquery.min.js"></script>
    <script>
        //点击全选的checkbox,让下面所有人名前的checkbox的选中状态和全选的一致
        $('#ch_all').on('click', function () {
      
      
            $('.j-chbox').prop('checked', $(this).prop('checked'))
        })
        //点击反选按钮,所有人名前的checkbox的选中状态取反
        $('button').on('click', function () {
      
      
            //遍历所有的input标签,让当前遍历到的元素的复选框的选中状态取反
            $('ul input').each(function (i, item) {
      
      
                $(item).prop('checked', !$(item).prop('checked'))
            })
            //遍历结束后重新判断,根据单选框的选中个数判断全选的选中状态
            if ($('.j-chbox:checked').length == $('.j-chbox').length) {
      
      
                $('#ch_all').prop('checked', true)
            } else {
      
      
                $('#ch_all').prop('checked', false)
            }
        })
        //点击所有人名前的checkbox,判断全选的选中状态
        // function j_box() {
      
      
        $('.j-chbox').on('change', function () {
      
      
            //:checked 选择器      :checked 查找被选中的表单元素。(获取被选择的复选框、单选框)
            if ($('.j-chbox:checked').length == $('.j-chbox').length) {
      
      
                $('#ch_all').prop('checked', true)
            } else {
      
      
                $('#ch_all').prop('checked', false)
            }
        })
    </script>
</body>
</html>

上述代码实现结果如下
全选反选效果
注意:使用时记得自己引用jQuery.js文件

猜你喜欢

转载自blog.csdn.net/qq_45093219/article/details/117306228