使用本地存储存储“已检查"复选框以存储多个项目 [英] Store Checkbox 'Checked' with localstorage for multiple items
本文介绍了使用本地存储存储“已检查"复选框以存储多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将复选框保存到本地存储,但是我正在使用的这段代码对于多个复选框来说太麻烦了…….有没有更好的方法呢?
I want to save my checkboxes to localstorage, but this code I am using would be too cumbersome for multiple checkboxes.... is there a better way to do this?
setStatus = document.getElementById('LineOp');
setStatus.onclick = function() {
if(document.getElementById('LineOp').checked) {
localStorage.setItem('LineOp', "true");
} else {
localStorage.setItem('LineOp', "false");
}
}
getStstus = localStorage.getItem('LineOp');
if (getStstus == "true") {
alert("Welcome Back");
document.getElementById("LineOp").checked = true;
} else {
console.log("News");
}
推荐答案
在这里,您可以根据需要放置任意多个复选框,只需添加具有本地存储唯一标识符的store属性. JSFiddle
Here is a way where you could put as many checkboxes as you want, just add the store attribute with a unique identifier for local storage. JSFiddle
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
这篇关于使用本地存储存储“已检查"复选框以存储多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文