<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>table分页多选</title>
<link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body>
<table id="demo" lay-filter="demo"></table>
<script src="layui/layui.all.js"></script>
<script>
layui.use('table', function () {
let table = layui.table
, form = layui.form
, $ = layui.$;
// 设置全局变量以保存选中行信息
let ids = new Array();
// 保存当前页全部数据id,点击全选时使用
let tableIds = new Array();
table.render({
elem: '#demo'
,url: '/user.js'
,cols: [[
{type:'checkbox'}
,{field:'id', width:80, title: 'ID', sort: true}
,{field:'username', width:80, title: '用户名'}
,{field:'sex', width:80, title: '性别', sort: true}
,{field:'city', width:80, title: '城市'}
,{field:'sign', title: '签名', minWidth: 100}
,{field:'experience', width:80, title: '积分', sort: true}
,{field:'score', width:80, title: '评分', sort: true}
,{field:'classify', width:80, title: '职业'}
,{field:'wealth', width:135, title: '财富', sort: true}
]]
,page: true
, done: function (res) {
// 设置当前页全部数据id到全局变量
tableIds = res.data.map(function (value) {
return value.id;
});
// 设置当前页选中项
$.each(res.data, function (idx, val) {
if (ids.indexOf(val.id) > -1) {
val["LAY_CHECKED"] = 'true';
//找到对应数据改变勾选样式,呈现出选中效果
let index = val['LAY_TABLE_INDEX'];
$('tr[data-index=' + index + '] input[type="checkbox"]').click();
form.render('checkbox'); //刷新checkbox选择框渲染
}
});
// 获取表格勾选状态,全选中时设置全选框选中
let checkStatus = table.checkStatus('demo');
if (checkStatus.isAll) {
$('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
form.render('checkbox'); //刷新checkbox选择框渲染
}
}
});
// 监听勾选事件
table.on('checkbox(demo)', function (obj) {
if (obj.checked == true) {
if (obj.type == 'one') {
ids.push(obj.data.id);
} else {
for (let i = 0; i < tableIds.length; i++) {
//当全选之前选中了部分行进行判断,避免重复
if (ids.indexOf(tableIds[i]) == -1) {
ids.push(tableIds[i]);
}
}
}
} else {
if (obj.type == 'one') {
let i = ids.length;
while (i--) {
if (ids[i] == obj.data.id) {
ids.splice(i, 1);
}
}
} else {
let i = ids.length;
while (i--) {
if (tableIds.indexOf(ids[i]) != -1) {
ids.splice(i, 1);
}
}
}
}
});
})
// 一个页面有多个表格需要跨页多选时,回显选中行需要加上对应表格的选择器(包括全选的回显)
///$('#Table1 tr[data-index=' + index + '] input[type="checkbox"]').click();
// 如果是单选表格只需要记录选中行id就行,回显的写法将checkbox改为radio就行
// done: function (res, curr, count) {
// if (userId != '') {
// $.each(res.data, function (idx, val) {
// // 根据用户id回显
// if (userId == val.id) {
// val["LAY_CHECKED"] = 'true';
// //找到对应数据改变勾选样式,呈现出选中效果
// let index = val['LAY_TABLE_INDEX'];
// $('tr[data-index=' + index + '] input[type="radio"]').click();
// form.render('radio'); //刷新radio选择框渲染
// }
// });
// }
// }
</script>
</body>
</html>
layui的table分页多选
于 2022-10-11 15:40:23 首次发布