2016-07-09 8 views
0

ローカルキーストアにデータを保存するときにキー値を増やす必要があります。これは、すべてのレコードで同じキーを使用し、更新のみを記録するためです。私は閉鎖ビットでこれを行うことができることを知っている私は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

最初の手順として、コードをより読みやすくするように書式設定する必要があります。 (ex http://www.danstools.com/javascript-beautify/) –

+0

hasTicket = trueまたはfalse、 を保存する必要があります(hasTicket)//他のものをStorageに書き換えます。なぜそうしようとしませんか? –

+0

あなたのコードにクロージャは表示されません。すぐに呼び出される関数の式はクロージャ変数なしでは不要です。1セッション中またはセッション間でキーをインクリメントする必要があるかどうかは不明です。新しいキー – Aprillion

答えて

-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; 

     }()); 
    } 
    } 

})(); 
+0

これは動作しません。 –

+0

@ R.Prozがコードを作成し、完全なコードを表示します –

関連する問題