我想在单击按钮到lolalStorage时保存每个ID。将数组存储到localStorage中,每次点击一个按钮
$("li").on("click", "a", function(){
var test = {"id": id, "name":name};
localStorage.setItem("test", JSON.stringify(test));
});
但是在页面重新加载时,我只能得到一个id。
我想在单击按钮到lolalStorage时保存每个ID。将数组存储到localStorage中,每次点击一个按钮
$("li").on("click", "a", function(){
var test = {"id": id, "name":name};
localStorage.setItem("test", JSON.stringify(test));
});
但是在页面重新加载时,我只能得到一个id。
您在每次点击时覆盖同一项目,因此您只能存储最后一个。 test
是这个价值的关键。
你有两个选择:
1.-使用id
存储在localStorage的信息或产生与信息的新对象。
使用id
为localStorage的关键:
$("li").on("click", "a", function(){
localStorage.setItem(id, name);
});
这样,你不知道哪个ID的你已经在本地存储,所以它的复杂事后检索信息。
2.-另一种选择是保存一个包含所有键值对象的数组。您将只存储一个对象的localStorage包含多个对象:
$("li").on("click", "a", function(){
var test = localStorage.getItem("test");
var obj = [];
if(test){
obj= JSON.parse(test);
}
obj.push({"id": id, "name":name});
localStorage.setItem("test",JSON.stringify(obj));
});
所以后来检索信息是因为这样做很容易:
var test = JSON.parse(localStorage.getItem("test")); // Returns array with multiple objects
由于localStorage每次都使用相同的密钥“test”,因此每次点击都覆盖相同的值。尝试使用
localStorage.setItem(id, name);
如果您存储的数据相同的变量例如'test',那么你只会存储一个对象,最后一个被保存。您需要使用可能基于对象ID的不同键,以存储不同的对象并能够检索它们。 – melc