我点击按钮时尝试将数据保存到localstorage。但是,当我单击按钮键总是0并且我更新记录时,不要创建新记录,因为key = 0.我尝试通过闭包增加键值,但我在JS中是非常新的并且我的"返回"不起作用。 (
function() {
window.onload = function() {
var key = 0;
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 storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
return ++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)
您需要在key
函数之外初始化onclick
,否则每次单击时都会将其设置为0。您不需要在内部函数中执行增量。
每次点击时也无需创建新的Storage
,也可以在开头创建一次。
function() {
var key = 0;
var storage = new Storage();
window.onload = function() {
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++;
}
}
})();