前言
记录一下实现全选/全不选、单项复选框点击,以及这两者之间的相互联动关系。提示:以下是本篇文章正文内容,下面案例可供参考
一、复选框
1.1 需求
① 选中全选框,可以选中当前页面的所有数据(所有数据前的复选框自动选中),取消选中全选框满所有记录前的单选框自动取消
② 当所有的单选框全部选中时,全选框也自动选中,当当前页面的数据有未选中项时,全选框没有选中
代码:
<form action="/category/deleteBatch" id="df">
<table id="simple-table" class="table table-bordered table-hover">
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>编号</th>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 数据回显 -->
<tr th:each="cate, status : ${page.list}">
<td>
<input type="checkbox" name="id" th:value="${cate.categoryId}">
</td>
<td th:text="${cate.categoryId}">1</td>
<td th:text="${cate.categoryName}">名字</td>
<td>
<div class="hidden-sm hidden-xs btn-group">
<a class="btn btn-xs btn-info"
th:href="|/category/toUpdate/${cate.categoryId}|">
<i class="ace-icon fa fa-pencil bigger-120"></i>
</a>
<a class="btn btn-xs btn-info" th:href="|/category/delete/${cate.categoryId}|">
<i class="ace-icon fa fa-trash-o bigger-120"></i>
</a>
</div>
</td>
</tr>
</tbody>
</table>
</form>
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
1.2 js事件
<script>
$(function () {
// 全选全不选
$("#checkAll").click(function () {
var flag = $("#checkAll").prop("checked")
var idList = $("input[name='id']");
for (var i = 0; i < idList.length; i++) {
$(idList[i]).prop("checked", flag);
}
});
// 单个复选框
$("input[name='id']").click(function () {
var checkAll = $("#checkAll");
var idList = $("input[name=id]");
for (var i = 0; i < idList.length; i++) {
if ($(idList[i]).prop("checked") == false) {
checkAll.prop("checked", false);
return;
}
}
checkAll.prop("checked", true);
});
</script>
二 、总结
① 这个功能其实不难,逻辑好想,就是点击全选框时,把全选框的checked选中状态,同步到每一条数据前的复选框中;
② 单条数据的选中或者取消选中,都要对当前页面的所有数据的复选框选中状态进行判断,并以此对全选框的状态进行操作。
③ 这个页面还有个批量删除的功能,就是在①②的多选基础上,将选中的复选框的值,提交到后端,进行接收处理,后端接收字段的名称要和前端页面的保持一致;