HTML5について勉強中
入門編の備忘録
WebStorage 入門 その3
データベースアプリのサンプルを打ち込んで動かしてみる
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport"
content="initial-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"
/>
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css"
/>
<title>Sample Test</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script type="text/javascript" src="js/test.js"></script>
<script type="text/javascript">
</script>
</head>
<body onload="load()">
<div data-role="page">
<header data-role="header" dataposition="fixed">
<h1>見出し</h1>
</header>
<div data-role="content">
<p>メインコンテンツ</p>
<form>
日付:<input type="date" id="input1" required><br>
内容:<input type="text" id="input2" required><br>
<button type="button" onclick="input()">追加</button>
</form>
<div id="output">
<table border cellpadding="5">
<tr>
<th>日付</th><th>内容</th><th>削除</th>
</tr>
</table>
</div>
</div>
<footer data-role="footer" dataposition="fixed">
フッター
</header>
</div>
</body>
</html>
同ディレクトリにjsディレクトリ作ってその中にtest.jsを作る
その中に関数書いて読み込んでいる
test.jsの中身
var a = new Array();
//HTML文書読み込み完了
function load() {
var ls = localStorage.getItem("action");
if(ls != null){
a = JSON.parse(ls);
}else{
a = [];
}
show();
}
//入力
function input(){
if(document.getElementById("input1").value =="" ||
document.getElementById("input2").value ==""){
alert("input date and plan")
}else{
a.push({"date":document.getElementById("input1").value,
"memo":document.getElementById("input2").value});
save();
}
}
//i番目を削除
function deleteValue(i){
a.splice(i,1);
save();
}
function show(){
var s = '<table border ' +
'cellpadding = "5" ' +
'<tr><th>日付</th><th>内容</th><th>削除</th></tr>';
sort();
for(var i=0;i<a.length; i++){
s += "<tr>";
for(var p in a[i]){
s+="<td>" + a[i][p] + "</td>";
}
s += '<td><button onclick ="deleteValue('
+ i +')">削除</button></td>';
s += "</tr>";
}
s += "</table>";
document.getElementById("output").innerHTML = s;
}
function save(){
localStorage.setItem("plan",JSON.stringify(a));
show();
}
function sort(){
for(var i =0;i<a.length;i++){
a[i] = JSON.stringify(a[i]);
}
a.sort();
for(i =0;i<a.length;i++){
a[i] = JSON.parse(a[i]);
}
}
日経ソフトウェア2013年1月号から