2012-01-19 10 views
2

このLocalStorage機能を使用して、連絡先情報をユーザーのコンピュータに保存する連絡先リストスタイルアプリケーションを作成したいと考えています。2つ以上の値を持つHTML5 LocalStorage

今、私が抱えている問題は、私が知る限り、エントリごとに2つの値しか格納できないということです。名前と値。

私はこれを回避する方法を考えることができないので、私は少し損失があります。助言がありますか?私は、特定のエントリについて約4/5フィールドの情報を格納することを望んでいます。

よろしく、 ジャック・ハント

+2

文字列の 'JSON'ですか? –

+1

@Marekそれはかなり妥当と思われる –

+1

@MarekSebera - あなたは答えとして投稿する必要があります。それは誰もがそれを行う方法はかなりです。 – Anurag

答えて

5

は、String形式

// myCollection contains three objects, filled with custom type data, in array 
var myCollection = [{},{},{}] 
function replacer(key, value) { 
    if (typeof value === 'number' && !isFinite(value)) { 
     return String(value); 
    } 
    return value; 
} 
localStorage['first_collection'] = JSON.stringify(myCollection, replacer); 

でJSONとして別々のキーフィールドの各データ型のコレクションを保存することを考慮すると、あなたが疑問に思うならば、そこにある理由replacer機能は、以下の最初のリンクを見てみましょうということ。
それは、私はこの前に、私はそれが一種の汚れだ場合は知っているが、それはありませんでしたjson.org

http://www.json.org/js.html
JSON to string variable dump
JSON to string in Prototype
https://developer.mozilla.org/en/JSON
http://api.jquery.com/jQuery.parseJSON/

+1

ありがとう、ありがとう。今私はJSONについて読んでいます。あなたはそれを見たことがありません。その間にもJavaScriptは使用されていません。ありがとう。 –

+0

ようこそ@VisionIncision –

0

あなたはJSONオブジェクトとしてのlocalStorageにデータを保存することができます。 KEYは "people"のようなもので、VALUEは "people"オブジェクトの配列になります。何らかのCRUDがjavascriptで発生し、LocalStorageは永続性媒体としてのみ使用されます。

0

によって直接物事のやり方をお勧めします私のために働く。私がやったことは、オブジェクトを格納できるようにStorageプロトタイプを書き直すことでした。

まず、私は、元のメソッド "保存":

Storage.prototype._setItem = Storage.prototype.setItem; 
Storage.prototype._getItem = Storage.prototype.getItem; 

そして、私は新しいものに書き換える:

localStorage.setItem('test', {value: 1}); // or localStorage.setItem('test', '{value: 1}') 
localStorage.setItem('test2', [3,2,1]); // or localStorage.setItem('test2', '[3,2,1]'); 
localStorage.setItem('test3', '{no object stuff'); 

これを持っ
Storage.prototype.setItem = function(key, object){ 
    if(typeof object == 'object'){ 
     this._setItem(key, JSON.stringify(object)); 
    } 
    else{ 
     this._setItem(key, object); 
    } 
} 
Storage.prototype.getItem = function(key){ 
    var val = this._getItem(key); 
    try{ 
     val = JSON.parse(val); 
    }catch(e){} 
    return val; 
} 

を、あなたはとしてそれを使用することができます

と同じデータを取得します。getItem

localStorage.getItem('test'); // Object: {value: 1} 
localStorage.getItem('test2'); // Array: [3,2,1] 
localStorage.getItem('test3'); // String: '{no object stuff' 
0
For Example we Have Two Input Element name and email, ok then we have to store key and value pair 

VAR名=のdocument.getElementById( 'DEMO1')値。

var email = document.getElementById( 'demo2')。value;

localStorage.setItem( "name"、name);

localStorage.setItem( "email"、email);

関連する問題