在使用bootstrap table的复选框功能的时候,由于采用服务端分页,当在第一页选择了某些数据,然后点击第二页选择一些数据,再次点回第一页,发现原先选择的数据已经清空了,原来的多选框并不支持翻页保留多选数据。
解决思路:在分页的时候,吧原先选择的数据用一个全局变量保存,当再次翻页回来时,判断当前页数据是否存在于保存的数据数组中,存在则状态为选择。当然当取消选择的时候也要去删除数组中相应的数据。
为了解决这个问题,在查github上查文档发现有人提出了这个问题,并且作者wenzhixin 也编写了相应的例子来演示,想看原问题的点击打开链接。
想直接看示例的点击打开链接
原示例是使用html方式来实现的表格,并使用服务端分页。并且相关js方法并不完善,我也踩了很多坑,所以本博客在原作者编写的示例的基础上,做了相关更改,在此展示和说明:
-
var $table;
-
var selectionIds = [];
//保存选中ids
-
$(
function () {
-
$table = $(
"#example1").bootstrapTable({
-
contentType:
"application/x-www-form-urlencoded; charset=UTF-8",
//初始化编码
-
url:
'<%=basePath%>/order/queryOrderList',
-
method:
'post',
-
striped:
true,
//奇偶行渐色表
-
pagination:
true,
//显示分页
-
clickToSelect:
true,
//是否选中
-
maintainSelected:
true,
-
sidePagination:
"server",
//服务端分页
-
idField:
"id",
-
pageSize:
10,
-
responseHandler:responseHandler,
//在渲染页面数据之前执行的方法,此配置很重要!!!!!!!
-
columns: [
-
{
field:
'checkStatus',
checkbox:
true},
//给多选框赋一个field值为“checkStatus”用于更改选择状态!!!!!
-
{
field:
'id',
visible:
false},
-
{
field:
'orderNumber',
title:
"订单编号",
align:
'center',
width:
'10%'}
-
]
-
});
-
//选中事件操作数组
-
var union =
function(array,ids){
-
$.each(ids,
function (i, id) {
-
if($.inArray(id,array)==
-1){
-
array[array.length] = id;
-
}
-
});
-
return array;
-
};
-
//取消选中事件操作数组
-
var difference =
function(array,ids){
-
$.each(ids,
function (i, id) {
-
var index = $.inArray(id,array);
-
if(index!=
-1){
-
array.splice(index,
1);
-
}
-
});
-
return array;
-
};
-
var _ = {
"union":union,
"difference":difference};
-
//绑定选中事件、取消事件、全部选中、全部取消
-
$table.on(
'check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table',
function (e, rows) {
-
var ids = $.map(!$.isArray(rows) ? [rows] : rows,
function (row) {
-
return row.id;
-
});
-
func = $.inArray(e.type, [
'check',
'check-all']) >
-1 ?
'union' :
'difference';
-
selectionIds = _[func](selectionIds, ids);
-
});
-
});
-
//表格分页之前处理多选框数据
-
function responseHandler(res) {
-
$.each(res.rows,
function (i, row) {
-
row.checkStatus = $.inArray(row.id, selectionIds) !=
-1;
//判断当前行的数据id是否存在与选中的数组,存在则将多选框状态变为true
-
});
-
return res;
-
}
原示例中并没有给出union和difference方法,是我自己按着思路实现的。开始并没有实现此功能,后来发现要给checkbox字段加上一个filed字段,并与responseHandler方法中更改的row字段一致,才能实现功能。
转载地址:https://blog.csdn.net/github_36086968/article/details/60773900