我想将我的复选框保存到本地存储,但是我使用的这段代码对于多个复选框来说太麻烦了......有没有更好的方法来做到这一点?
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 http://jsfiddle.net/n2eS3/3/
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);
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)