项目中需要翻页,但保持复选框的选中状态。本人的思路是将:选中的值存储在数组中,并将数组存储在localStorage中,翻页时判断页面是否包含当前数组存在的Id值,如果存在则将状态变为选中状态。
1、页面标签
这里data.Id绑定的页面数据中的Id
<td><input type="checkbox" value="@data.Id" name="ids" id="ids" /></td>
2、JS代码
$(document).ready(function (e) {
//页面加载时获取localStorage中的数组值
var arr = JSON.parse(localStorage.getItem('idsData'));
if (arr == null || arr == undefined)
{
window.localStorage.removeItem('idsData');
var arr = new Array();
}
//选中多选框
var checkbox = $("input[type='checkbox']");
//循环多选框中的值
checkbox.each(function () {
for (var j = 0; j < arr.length; j++) {
//判断当前值是否在数组中
if ($(this).val() == arr[j]) {
$(this).attr('checked', 'checked');//选中
}
}
});
//定义checkbox事件
$("input[type='checkbox']").change(function () {
if (this.checked) {
//选中往数组中添加值
arr.push($(this).val());
}
else {
//取消则删除数组中的值
arr.splice($.inArray($(this).val(),arr), 1);
}
//去重
var newArr = dedupe(arr);
//写入localStorage
localStorage.setItem('idsData', JSON.stringify(newArr));
});
});
//去重方法
function dedupe(array) {
return Array.from(new Set(array));
}