<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>HTML5本地存储之Web Storage篇</title>
</head>
<!--<script type="text/javascript" src="js/jquery-1.js"></script>
-->
<body onLoad="loadAll()">
<div style="border: 2px dashed #ccc;width:320px;text-align:center;">
<label for="user_name">姓名:</label>
<input type="text" id="user_name" name="user_name" class="text"/>
<br/>
<label for="mobilephone">手机:</label>
<input type="text" id="mobilephone" name="mobilephone"/>
<br/>
<input type="button" onClick="save()" value="新增记录"/>
<hr/>
<label for="search_phone">输入手机号:</label>
<input type="text" id="search_phone" name="search_phone"/>
<input type="button" onClick="find()" value="查找机主"/>
<p id="find_result"><br/></p>
</div>
<br/>
<div id="list">
</div>
<script type="text/javascript">
//保存数据
function save(){
var mobilephone = document.getElementById("mobilephone").value;
var user_name = document.getElementById("user_name").value;
localStorage.setItem(mobilephone,user_name);
loadAll();
}
//将所有存储在localStorage中的对象提取出来,并展现到界面上
function loadAll(){
var list = document.getElementById("list");
if(localStorage.length>0){
var result = "<table border='1' style='border-collapse:collapse;'>";
result += "<tr><td>姓名</td><td>手机号码</td><td>操作</td></tr>";
for(var i=0;i<localStorage.length;i++){
var mobilephone = localStorage.key(i);
var name = localStorage.getItem(mobilephone);
result += "<tr id='tab"+i+"'><td>"+name+"</td><td>"+mobilephone+"</td><td><a href='update()'>修改</a> <a href='javascript:;' οnclick=\"del('"+mobilephone+"','tab"+i+"')\">删除</a></td></tr>";
}
result += "</table>";
list.innerHTML = result;
}else{
list.innerHTML = "目前数据为空,赶紧开始加入联系人吧";
}
}
//查找数据
function find(){
var search_phone = document.getElementById("search_phone").value;
var name = localStorage.getItem(search_phone);
var find_result = document.getElementById("find_result");
find_result.innerHTML = search_phone + "的机主是:" + name;
}
//查找数据
function update(){
var mobilephone = document.getElementById("mobilephone").value;
var user_name = document.getElementById("user_name").value;
}
//查找数据
function del(tel,id){
var ls_t=document.getElementById(id);
ls_t.parentNode.removeChild(ls_t);
localStorage.removeItem(tel);
}
</script>
</body>
</html>