每次单击按钮时,我都希望使用不同的键将不同的对象保存到本地存储。但总是键== 0并且记录没有创建,本地存储中的一条记录只会更新,我认为这是因为密钥总是相同的。我如何改变这一点,将不同的对象放到本地存储?
(function() {
window.onload = function() {
var key = 0;
var storage = new Storage();
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
key++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
答案 0 :(得分:0)
您为keyName(第一个参数)设置了一个项目:
localStorage.setItem(keyName, keyValue);
您获得了一个keyName的项目:
var aValue = localStorage.getItem(keyName);
因此,在您的情况下,您的存储对象应该进行调整,因为您似乎需要多个密钥,但您的存储空间只会检索固定密钥='项目'。
因此,修改您的Storage.get并在调用时传递密钥:
function Storage() {
this._ITEMS_DESCRIPTOR = 'items'; // I guess a default key?
}
// let key be specified when method is called, or by default set it to the private property _ITEMS_DESCRIPTOR
Storage.prototype.get = function(key) {
var fromStorage = localStorage.getItem(key ? key : this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
答案 1 :(得分:0)
您的密钥应该递增,但您的storage.get被硬编码为特定密钥,因此您永远无法通过其get方法检索它们。
您还应该验证是否正在调用该方法
您可以尝试将字符串与数字作为键
storage.set("topic_" + key, ticket);
// alert("topic set for topic_" + key);
// retrieve and test data storage
// var data = localStorage.getItem("topic_" + key);
// alert("from storage:\n\n" + JSON.stringify(data));
key++;
使用F12查看localStorage或只测试存储的数据
function test(){
if (localStorage.length == 0)
alert("no items in localStorage");
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var value = localStorage.getItem(key);
alert("storage [" + key + "] = " + value);
}
}