新卒から文系エンジニア→人材業界に転職した人のブログ

新卒から文系エンジニア→人材業界に転職。技術・スキルがないためブログを通して勉強。その後、IT業界の業界知識が活かせる人材業界へ。異業種×異職種の転職経験有り。

このエントリーをはてなブックマークに追加

【HTML5・javascript】Webストレージを使って、登録・保存・検索・出力する

【今回の紹介】


掲題の通り、Webストレージを使って、登録・保存・検索・出力する処理をメモとして残します。

参考
Web Storageによるテキストデータの保存


【メモ】

①Webストレージ内はキーとバリューで管理されている
 
Webストレージ内はキーとバリューで管理されているということを理解していれば、
 登録・検索・変更などの処理は比較的な簡単にできる。



jsonで格納する際の手順

 今回の処理では、
 ①オブジェクトに値を格納する
 ②①の値をjsonの手文字列に変換
 ③Webストレージから取得時にjsonにパースする
 という手順をふんでいる。
 

【参考ソース】

<html>
<head>
<meta charset='utf-8'>
</head>
<title>HTML5</title>
<body>
	<h1>webstorage</h1>
	<span>ID:</span><input type='text' id='id'></input>
	<span>答え:</span><input type='text' id='answer'></input>
	<input type='button' id='button1' value='送信' onclick="saveStorage('input1');"></input>
	<input type='button' id='button2' value='読み込み' onclick="loadStorage();"></input>
	<input type='button' id='button3' value='初期化' onclick="clearStorage();"></input>

	<span>検索:</span><input type='text' id='serch_text'></input>
	<input type='button' id='button4' value='検索' onclick="serchStorage();"></input>
	<p id='output'></p>
<script>


//IDをキーに保存処理を行う
function saveStorage(){
	var obj={};
	obj.id=$("id").value;
	obj.answer=$("answer").value;
	var value=JSON.stringify(obj);
	localStorage.setItem(obj.id,value);
	}



//インデックスをもとにキーを取得し、値を出力する処理
function loadStorage(){
	var result='<table border="1">';
	for(var i=0;i<localStorage.length;i++){
		var key=localStorage.key(i);
		result+= '<tr><td>' + key +'</td><td>'+ localStorage.getItem(key) +'</td></tr>';
		}
	result+='</table>';
	$("output").innerHTML=result;
}


//ストレージ内のデータを削除する処理
function clearStorage(){
	localStorage.clear();
	loadStorage();
}


//IDをキーに検索を行う処理
function serchStorage(){
	var serch_text=$("serch_text").value;
	var result = JSON.parse(localStorage.getItem(serch_text));
	console.log(result.answer);
}

//DOMノードを取得する処理
function $(id){
	return document.getElementById(id);
}

</script>
</body>
</html>
.hatena-module:nth-of-type(10) { background: transparent; } .hatena-module:nth-of-type(10) .hatena-module-title{ display: none; } .hatena-module:nth-of-type(10) .hatena-module-body { padding: 0; }