Skip to content

Instantly share code, notes, and snippets.

@tango238
Created August 26, 2011 03:17
Show Gist options
  • Save tango238/1172602 to your computer and use it in GitHub Desktop.
Save tango238/1172602 to your computer and use it in GitHub Desktop.
[HTML5]Local Storage
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Local Storage</title>
</head>
<style>
p.success {
background-color: #0f0;
}
p.fail {
background-color: #f00;
}
</style>
<body>
<section id="wrapper">
<header>
<h1>Local Storage</h1>
</header>
<article>
<select id="list" size="5" style="width: 100px"></select>
<button id="btn-remove">Remove</button><br>
KEY:<input type="text" id="key"><br>
VAL:<input type="text" id="value">
<button id="btn-add">Add</button>
<p id="status">Not Supported</p>
</article>
</section>
<script>
(function(){
// ブラウザがAPIをサポートしているか
var status = document.getElementById('status');
if(!localStorage){
status.className = 'fail';
} else {
status.className = 'success';
status.innerHTML = 'Local Storage is available';
}
function load() {
var list = document.getElementById('list');
list.innerHTML = '';
// Local Storageに保存されているデータ分繰り返す
for (var i = 0; i < localStorage.length; i++) {
// Local Storageに保存されているキーを取得する
var key = localStorage.key(i);
// 取得したデータからOptionを作成。SELECT要素に追加していく
list.options[list.options.length] = new Option(key, key);
}
}
var btnRemove = document.getElementById('btn-remove');
btnRemove.onclick = function(){
var list = document.getElementById('list');
if (list.selectedIndex < 0) {
return;
}
// 選択されているインデックスの値を取得
var selected = list.options[list.selectedIndex].value;
// その値をキーにLocal Storageのデータを削除する
localStorage.removeItem(selected);
load();
};
var btnAdd = document.getElementById('btn-add');
btnAdd.onclick = function(){
// keyに入力されている値を取得する
var key = document.getElementById('key').value;
// valueに設定されている値を取得する
var value = document.getElementById('value').value;
// 取得したkeyとvalueでLocal Storageに保存する
localStorage[key] = value;
load();
};
load();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment