跨页选中多条数据
不同id区分全选框和复选框
<table class="am-table am-table-striped am-table-hover am-text-middle am-margin-top-sm">
<thead>
<tr>
<th>
<div><input type="checkbox" id="checkAll" name="checkbox" /></div>
</th>
</tr>
</thead>
<tbody>
{{foreach $data_list as $v}}
<tr id="data-list-{{$v.id}}" {{if $v['is_enable'] eq 0}}class="am-active"{{/if}}>
<td class="am-hide-sm-only"><input type="checkbox" id="checkbox" data="{{$v.id}}" name="checkbox" /></td>
</tr>
{{/foreach}}
</tbody>
</table>
因为我这个分页是跳页面的所以把选中的数据存到了session中,页面刷新要判定来源,不跳页面的话就简单多了直接把选中的数据存到一个全局变量里就好了
<script>
//判定全选框按钮是否应该选中
function set_checked(){
//如果当前页面未选中的复选框长度为0则全选框选中
if($("input[id='checkbox']").not("input:checked").length == 0){
$("#checkAll").prop("checked",true);
}else{
$("#checkAll").prop("checked",false);
}
}
//保存选中的数据
function set_ids(){
//获取所有选中的checkbox
$('input:checkbox[id=checkbox]:checked').each(function(i){
//如果数组里没有选中的数据就push进去
let id = $(this).attr('data');
let isin = $.inArray(id,ids);
if(isin == -1){
ids.push(id);
}
});
//获取所有未选中的checkbox
$("input[id='checkbox']").not("input:checked").each(function(i){
//如果数组里存在当前取消选中的数据就删掉
let id = $(this).attr('data');
let isin = $.inArray(id,ids);
if(isin != -1){
ids.splice(isin,1);
}
});
//存到session中
sessionStorage.setItem('ids', JSON.stringify(ids));
}
let ids = [];
$(document).ready(function(){
//判定上个页面来源 若分页链接进来则不清除session数据
lasturl = document.referrer;
begin = parseInt(lasturl.indexOf('='))+2;
end = parseInt(begin)+17;
method = lasturl.substring(begin,end);
if(method != 'couponcodechannel'){
sessionStorage.removeItem('ids');
}else{
//获取保存数据 选中对应复选框
ids = JSON.parse(sessionStorage.getItem('ids'));
$('input:checkbox[id=checkbox]').each(function(i){
let id = $(this).attr('data');
let isin = $.inArray(id,ids);
if(isin != -1){
$(this).prop("checked",true);
}
});
//判定全选框按钮是否应该选中
set_checked();
}
});
//全选框按钮点击事件
$("#checkAll").click(function () {
//如果全选框选中 复选框全部选中
if($("#checkAll").prop("checked") == true){
$("input:checkbox[name='checkbox']").prop("checked",true);
}else{
$("input:checkbox[name='checkbox']").prop("checked",false);
}
//保存选中的数据
set_ids()
});
//复选框按钮点击事件
$("input:checkbox[name='checkbox']").click(function () {
//判定全选框按钮是否应该选中
set_checked();
//保存选中的数据
set_ids()
});
</script>