当我将数据保存到localstorage时,我需要增加键值,因为当我单击按钮键对所有记录都相同并且记录只是更新时,不会创建新的。我知道我可以使用闭包装来做这件事,我在JS中很新鲜并且不知道如何做到这一点。
(function() {
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 key = 0;
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
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 :(得分:-1)
您需要在函数前声明变量,以保存值并添加1 +。
(function() {
window.onload = function() {
var key = 0; //move var key to here
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 key = 0; remove these line
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
return key;
}());
}
}
})();