gpt4 book ai didi

javascript - 将复选框 'Checked' 与多个项目的本地存储一起存储

转载 作者:行者123 更新时间:2023-11-29 17:06:25 25 4
gpt4 key购买 nike

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

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

最佳答案

这里有一种方法,您可以根据需要放置任意多个复选框,只需添加带有本地存储唯一标识符的商店属性。 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);
});
}

关于javascript - 将复选框 'Checked' 与多个项目的本地存储一起存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24461734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com