まず:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
そうでない場合には(質問に、あなたの変数のためのキー(名前を)持っていません)あなたの構造する必要があります。私は右のあなたを理解している場合は、オブジェクト(JSON)のような構造を持っています私はオブジェクトの各変数へのアクセスを持っているために示したようです。
第2:約localStorage
です。これは文字列のキーと値のペアのみを処理するために制限されているため、オブジェクトを保存することはできません。 JSON.stringify()
を使用してオブジェクトを文字列に解析し、localStorage
に保存してから、取得後にJSON.parse()
を使用して解析し直してください。コードは次のようになります。
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT:あなたの項目の名前がユニークであれば、あなたの質問が複数の項目を格納し、それらを区別する程度であり、あれば、そう
複数のアイテムを保存するためにはあなたはどのアイテムが購入されているかを知っていますが、アイテムの名前のキーを使ってlocalStorageにアイテムを保存することができます。
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));
http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – Viney