Help us understand the problem. What is going on with this article?

Web Storageの使用

More than 3 years have passed since last update.

HTML5ではlocalStorageという配列(オブジェクト)にデータを保存できる。保存はブラウザ単位に行われる。
sessionStorageという配列も同様だが、こちらは、ブラウザを閉じたときにデータは消える。

HTMLの例

<input type="text" id="input">
<input type="button" value="保存" id="save">
<input type="button" value="読み込み" id="load">`

スクリプトの例

$(function(){
    $("#save").click(function(){
        var str = $("#input").val();
        localStorage["test"] = str;
    });

    $("#load").click(function(){
        var str = localStorage["test"];
        $("#input").val(str);
    });
});

メソッド

機能 メソッド
保存 setItem(key,value)
取得 getItem(key)
削除 removeItem(key)
クリア clear()

補足:保存に便利な JSON.stringify と JSON.parse

WebStorageでは、一つのキーに一つしかデータを保存できず、配列の表現も難しい。このため、オブジェクトを文字列化し、保存すると便利である。

JSONデータを文字列化するJSON.stringify
例:

    var obj = {sname:"りんご",tanka:100};
    alert( JSON.stringify(obj) );

文字列化したJSONデータをオブジェトにするJSON.parse
例:

    var str = '{"sname":"りんご","tanka":100}';
    var obj = JSON.parse(str);
    alert( obj.sname ); 
dicre
シェアウェア作家
http://www.dicre.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした