2016-07-09 5 views
0

ボタンをクリックしたときにローカルストレージにデータを保存しようとしています。しかし、ボタンのキーを常に0にしてレコードを更新すると、キー= 0なので新しいレコードを作成しません。私はクロージャを使ってキー値を増やしていますが、JSでは非常に新しいので、 "return"は機能しません。あなたが内部関数で増分を行う必要はありません。それ以外の場合は0に戻り、あなたがクリックするたびに設定されます、onclick関数の外keyを初期化する必要が (ボタンをクリックしたときのキー値の変更

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)); 
}; 
+1

'与えられたキーを使用して取るset'が、' GET'は常に '_ITEMS_DESCRIPTOR'を使用しない理由どのように'set'で保存したアイテムを取得しますか? – Barmar

答えて

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++; 
     } 
    } 
})(); 
関連する問題