问题
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");
}
回答1:
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);
});
}
回答2:
Since you are using jQuery, try:
var getStstus = localStorage.getItem('LineOp');
if (getStstus === "true")
$("#LineOp").prop("checked", true);
$("#LineOp").click(function(){
localStorage.setItem('LineOp', $(this).prop("checked"));
});
jsFiddle
来源:https://stackoverflow.com/questions/24461734/store-checkbox-checked-with-localstorage-for-multiple-items