Store Checkbox 'Checked'使用本地存储存储多个项目

Store Checkbox 'Checked' with localstorage for multiple items

本文关键字:存储 项目 Checkbox Checked Store      更新时间:2023-09-26

我想将复选框保存到本地存储,但是我使用的这段代码对于多个复选框....来说太麻烦了有更好的方法吗?

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

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); 
    });
}

既然你正在使用jQuery,试试:

var getStstus = localStorage.getItem('LineOp');
if (getStstus === "true")
    $("#LineOp").prop("checked", true);
$("#LineOp").click(function(){
    localStorage.setItem('LineOp', $(this).prop("checked"));
});

jsFiddle