最近作项目,发现使用bootstrap table插件时,若是有复选框选择功能,翻页操做会致使上一页选中的丢失,而api中的 bootstrapTable('getSelections'); 只能拿到当前页的复选框,若是要实现翻页以后保留先前选中数据,须要作下面逻辑处理bootstrap
var checkedIds = [] //存放选中的id var checkedNames= [] //存放选中的须要的其余信息,若是只须要id,能够不用这个字段 $(function() { $('#bootstrap-table').bootstrapTable({ url:'', search : true, toolbar : '#toolbar', //工具栏 sortable: true, //开启排序 cache : false, striped : true, singleSelect : false, locale : 'zh-CN', sidePagination : "server", clickToSelect : true, //是否启用点击选中行 pagination : true, maintainSelected : true,//若是是客户端分页,这个设为 true 翻页后已经选中的复选框不会丢失 pageSize : 10, pageNumber : 1, pageList: [10, 20, 30, 40], showRefresh : true, //是否显示刷新按钮 columns :[ { checkbox: true,// 显示复选框 formatter: function (i,row) { //判断当前id是否在存放选中id的数组中 if($.inArray(row.id,checkedIds )!=-1){ return { checked : true //若是存在,设置选中 } } } }, { field : 'name', title : '名称', }, ] }); $('#bootstrap-table').on('uncheck.bs.table check.bs.table check-all.bs.table uncheck-all.bs.table',function(e,rows,pageData){ let datas = $.isArray(rows) ? rows : [rows]; // 点击时获取选中的行或取消选中的行 //这里有个特殊状况,当有全选功能时,若是全选而后取消获得的rows值为空数组,因此此时取值取pageData //经过e.type的值判断是否点击的是全选按钮 e.type == 'uncheck-all' ? filterData(e.type,allData) : filterData(e.type,datas) }); });
/* 按要求对数据进行过滤,将选中的数据保存 */ function filterData(type,datas){ if(type == 'uncheck-all'){ //当全选取消选中项的时候,获取到当前页全部数据, $.each(datas,function(i,v){ if(v['0']==true){//若是为true说明是选中 checkedIds.indexOf(v.id) == -1 ? checkedIds.push(v.id) : -1; checkedNames.indexOf(v.name) == -1 ? checkedNames.push(v.name) : -1; }else{//说明是未选中 checkedIds.splice(checkedIds.indexOf(v.id),1); //删除取消选中行 checkedNames.splice(checkedNames.indexOf(v.name),1); } }); return } if(type.indexOf('uncheck')==-1){ $.each(datas,function(i,v){ // 添加时,判断一行或多行的 id 是否已经在数组里 不存则添加 checkedIds.indexOf(v.id) == -1 ? checkedIds.push(v.id) : -1; checkedNames.indexOf(v.name) == -1 ? checkedNames.push(v.name) : -1; }); }else{ $.each(datas,function(i,v){ checkedIds.splice(checkedIds.indexOf(v.id),1);//删除取消选中行 checkedNames.splice(checkedNames.indexOf(v.name),1); }); } }