2016-07-10 53 views
0

我想递增我的i值以将不同的值保存到本地存储。但我总是= 0,我能做些什么来改变这种行为?函数中的递增值

(function() { 
    var i = 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("task-"+i, ticket); 
     i++; 

     } 
    } 
})(); 
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

在将'i'设置为'0'之后立即调用'storage.set',并且在这之间永不增加值。除了每次将其声明为“0”以外,如果它存在,则将其设置为存储器中项目的值。另外一定要增加,然后调用'storage.set'。 –

+0

我已经评论过您的[上一个问题](http://stackoverflow.com/questions/38279021/incrementing-key-value-to-save-data-in-localstorage),您没有获取先前存储的值。 – Rajesh

+0

我如何获取以前存储的值? –

回答

2

声明var i = 0以外的函数。现在它每次运行时都会被重置为0。

+0

'window.onload'只运行一次。随着'(function(){...})()'中的项目运行一次。所以我不知道会做什么。 –

+0

使我的全球? –