在你所需要改动的页面,增加下边这一段代码,其中idsData可以自己定义,需要注意的是如果多个页面的数据源是一样的,每页的localStorage.getItem('*****')
*****最好不要一样,否则只要不清理浏览器缓存,一个页面选中复选框,其他有这段代码的页面也会选中。
复选框选择的内容会被存储到arr数组中,根据自己的需要去使用即可。
$(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));
}