web存储的小案例,localStorage和sessionStorage用法一样,区别在于localStorage是永久存储,sessionStorage是临时存储,我们一起通过这个小例子来学习一下。
h5部分代码
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box1,.box2{
width: 300px;
border:1px dashed #ccc;
margin: 0 auto;
padding: 20px;
margin-bottom: 20px;
}
h1{
text-align: center;
}
#p,#w{
width: 170px;
margin-top: 20px;
}
#btn{
display: block;
margin: 0 auto;
margin-top: 20px;
}
.box2 input[type="button"]{
margin-top:10px ;
}
.box2 p{
text-align: center;
margin-top:10px;
}
.box2 #show{
text-align: center;
margin-top:10px;
color: red;
}
#table{
width:340px;
margin: -20px auto;
}
</style>
</head>
<body>
<div class="box1">
<h1>存储信息</h1>
<lable>
网站名(key):<input type="text" id="p" value="" placeholder="网站名" />
</lable><br>
<lable>
网址(value):<input type="text" id="w" value="" placeholder="网址名" />
</lable>
<input type="button" value="存储信息" id="btn" onclick="save()"/>
</div>
<div class="box2">
<h1>查询信息</h1>
<lable>
网站名(key):<input type="text" id="q" value="" placeholder="网站名" />
</lable>
<input type="button" value="查询信息" onclick="find()" style="margin-left: 50px;"/>
<input type="button" value="删除信息" onclick="del()"/>
<input type="button" value="删除全部" onclick="delect()"/>
<p>您查询的网址为:</p>
<h2 id="show"></h2>
</div>
<table border="1" cellpadding="0" cellspacing="0" id="table">
</table>
</body>
js部分代码
var p =document.getElementById('p');
var w =document.getElementById('w');
var q =document.getElementById('q');
var table=document.getElementById('table')
//保存
function save(){
var names=p.value;
var url=w.value;
localStorage.setItem(names,url);
bianli();
}
//查找
function find(){
var fnames=q.value;
if(localStorage.getItem(fnames)){
show.innerHTML=localStorage.getItem(fnames);
}else{
show.innerHTML='查找的内容不存在';
}
}
//删除
function del(){
var fnames=q.value;
if(confirm("确定要删除吗")){
if(localStorage.getItem(fnames)){
localStorage.removeItem(fnames);
}else{
show.innerHTML='删除的信息不存在';
}
}
bianli();
}
//全部删除
function delect(){
if(confirm(“确定要全部删除吗”)){
localStorage.clear();
}
bianli();
}
//遍历数据
function bianli(){
var str=’<tr><td>网站名(key)</td><td>网址(value)</td></tr>’;
for(var i=0;i<localStorage.length;i++){
str+=’<tr><td>’+localStorage.key(i)+’</td><td>’+localStorage.getItem(localStorage.key(i))+’</td></tr>’;
}
table.innerHTML=str;
}
bianli();