jQuery 全选,反选,取消

阅读目录

预览

在这里插入图片描述

源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
	<!--引入jquery库-->
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<button id="all">全选</button>
<button id="reverse">反选</button>
<button id="cancel">取消</button>
<table border="1">
   <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
    </tr>
   </thead>
    <tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>郭德纲</td>
        <td>开车,京剧</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>岳云鹏</td>
        <td>做饭</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>于谦</td>
        <td>喝酒,抽烟,烫头</td>
    </tr>
    </tbody>
</table>


<script>
// 点击全选按钮 选中所有的checkbox
// DOM绑定事件方法
// $("#all")[0].onclick = function(){}
// jQuery绑定事件方法
$("#all").click(function () {
      
      
    $(":checkbox").prop('checked', true);
});
// 取消
$("#cancel").on("click", function () {
      
      
     $(":checkbox").prop('checked', false);
});
// 反选
$("#reverse").click(function () {
      
      
    // 1. 找到所有选中的checkbox取消选中
    // $("input:checked").prop('checked', false);
    // // 2. 找到没有选中的checkbox选中
    // $("input:not(:checked)").prop('checked', true);
    //你会发现上面这么写,不行,为什么呢?因为你做了第一步操作之后,再做第二步操作的时候,所有标签就已经全部取消选中了,所以第二步就把所有标签选中了

    // 方法1. for循环所有的checkbox,挨个判断原来选中就取消选中,原来没选中就选中
    var $checkbox = $(":checkbox");
    for (var i=0;i<$checkbox.length;i++){
      
      
        // 获取原来的选中与否的状态
        var status = $($checkbox[i]).prop('checked');
        $($checkbox[i]).prop('checked', !status);
    }
    // 方法2. 先用变量把标签原来的状态保存下来
//     var $unchecked =  $("input:not(:checked)");
//     var $checked = $("input:checked");
//
//     $unchecked.prop('checked', true);
//     $checked.prop('checked', false);
})

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

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/123894824