以下是我将如何构建数据(不严格):
var checkboxes = {
"key-1": { // might as well do to say: "key-1": true/false
"checked": true
},
"key-2": {
"checked": false
},
...,
"key-n-1": {
"checked": true/false
},
"key-n": {
"checked": true/false
}
};
以下是我将如何定义更新函数:
function updateStorage(){
var serialisedData = JSON.stringify(checkboxes);
localStorage.setItem("checkboxes-state", serialisedData);
};
以下是我将如何读取存储的数据:
function readStorage(){
var serialisedData = localStorage.getItem("checkboxes-state");
// then deserialise it
var data = JSON.parse(serialisedData);
// it may be empty
if(!data){
checkboxes = {}; // if empty initialise it
} else {
checkboxes = data;
}
}
以下是我将如何使用读取的数据更新 DOM 中适当元素的状态,并在复选框状态更改时更新数据:
d3.selectAll(".box").each(function(){
if(checkboxes.hasOwnProperty(this.id)){
this.checked = checkboxes[this.id].checked;
}
}).on("change", function(){
if(checkboxes.hasOwnProperty(this.id)){
checkboxes[this.id].checked = this.checked;
}else{
checkboxes[this.id] = {
"checked": this.checked
};
}
});
频繁读/写存储没有意义。理想情况下,对于大多数正常用例,每个会话读取一次就足够了。并且至少需要保存一次。
你可以细化你的问题,我可以给你更具体的答案。
把它们放在一起
var checkboxes = {
"key-1": { // might as well do to say: "key-1": true/false
"checked": true
},
"key-2": {
"checked": false
},
...,
"key-n-1": {
"checked": true/false
},
"key-n": {
"checked": true/false
}
};
var updateStorage = function(){
var serialisedData = JSON.stringify(checkboxes);
localStorage.setItem("checkboxes-state", serialisedData);
};
var readStorage = function(){
var serialisedData = localStorage.getItem("checkboxes-state");
// then deserialise it
var data = JSON.parse(serialisedData);
// it may be empty
if(!data){
checkboxes = {}; // if empty (i.e. if this was the first time the application was run on the current client) initialise it
} else {
checkboxes = data; // if we have data, restore it by assigning it to `checkboxes` variable
}
// having read the checkboxes states from the local storage, we reflect the read data on the DOM
d3.selectAll(".box").each(function(){
if(checkboxes.hasOwnProperty(this.id)){
this.checked = checkboxes[this.id].checked;
}
});
};
// on application load, read the storage
readStorage();
// bind the update function to its trigger button
d3.select("#update").on("click", updateStorage);
// update the `checkboxes` variable whenever user makes changes in selections
d3.selectAll(".box").on("change", function(){
if(checkboxes.hasOwnProperty(this.id)){
// update existing entry
checkboxes[this.id].checked = this.checked;
}else{
// add new entry and set its state
checkboxes[this.id] = {
"checked": this.checked
};
}
});
所以你去。