jQuery 全选,反选,取消
jQuery 取消 全选 反选
2023-09-11 14:14:56 时间
预览
源码
<!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>
相关文章
- jQuery显示隐藏密码插件jquery.toggle-password演示
- jquery中事件委派代码分析以及jQuery中delegate和on的用法与区别详细解析
- 第一百九十节,jQuery,编辑器插件
- js/jquery/插件表单验证
- jQuery 事件 - triggerHandler() 方法
- jquery中input和select中option选中和取消选中
- 电子签章盖章之jQuery插件jquery.zsign
- [jQ] 使用jQuery将多条数据插入模态框的方法
- jQuery plugin 开发的一个例子
- jQuery UI 为什么使用部件库(Widget Factory)
- jquery获取表单数据方法$.serializeArray()获取不到disabled的值
- 待续未完- 自己写后台内容管理程序 - 用tp框架 和 前台 jquery ui等写的
- jquery左右链接类似frameset的插件
- i18n 和 基于js的网页多语言框架 jquery.i18n的介绍
- jQuery EasyUI 布局 - 创建标签页(Tabs)