我想将我的复选框保存到localstorage,但是我使用的这段代码对于多个复选框来说太麻烦了....有没有更好的方法呢?
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");
}
答案 0 :(得分:3)
以下是一种可以根据需要添加多个复选框的方法,只需添加具有本地存储的唯一标识符的store属性即可。 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);
});
}
答案 1 :(得分:2)
由于您使用的是jQuery,请尝试:
var getStstus = localStorage.getItem('LineOp');
if (getStstus === "true")
$("#LineOp").prop("checked", true);
$("#LineOp").click(function(){
localStorage.setItem('LineOp', $(this).prop("checked"));
});