版权声明:部分来源于网络仅供学习交流 https://blog.csdn.net/Chad97/article/details/83385229
特性
- 设置、读取方便
- 容量较大,sessionStorage约5M、localStorage约20M
- 只能存储字符串,可以将对象JSON.stringify() 编码后存储
- window.sessionStorage
- 生命周期为关闭浏览器窗口
- 在同一个窗口(页面)下数据可以共享
- window.localStorage
- 永久生效,除非手动删除(服务器方式访问然后清除缓存)
- 可以多窗口(页面)共享
方法
- setItem(key, value) 设置存储内容
- getItem(key) 读取存储内容
- removeItem(key) 删除键值为key的存储内容
- clear() 清空所有存储内容
小栗子——模拟历史记录储存
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>首页</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
margin-left: 300px;
}
ul{
list-style: none;
}
ul li,div{
width: 250px;
padding: 10px 0;
margin-left: 10px;
border-bottom: 1px dashed #ccc;
height: 20px;
}
a{
float: right;
}
input{
padding: 5px;
margin: 10px;
}
</style>
</head>
<body>
<input type="search" placeholder="输入搜索关键字"/>
<input type="button" value="搜索"/>
<div><a href="javascript:;">清空搜索记录</a></div>
<ul>
<li>没有搜索记录</li>
<li><span>手机</span><a href="javascript:;">删除</a></li>
<li><span>手机</span><a href="javascript:;">删除</a></li>
<li><span>手机</span><a href="javascript:;">删除</a></li>
<li><span>手机</span><a href="javascript:;">删除</a></li>
<li><span>手机</span><a href="javascript:;">删除</a></li>
</ul>
<script src="jquery.min.js"></script>
<script>
$(function () {
/*1.默认根据历史记录渲染历史列表*/
var historyListJson=localStorage.getItem('historyList')||'[]';
var historyListArr = JSON.parse(historyListJson);
var render =function () {
var html='';
historyListArr.forEach(function (item,i) {
html+='<li><span>'+item+'</span><a data-index="'+i+'" href="javascript:;">删除</a></li>'
});
html=html||'<li>没有搜索记录</li>';
$('ul').html(html);
}
render();
/*2.点击搜索的时候更新历史记录渲染列表*/
$('[type="button"]').on('click',function () {
let key=$.trim($('[type="search"]').val());//trim去除左右空字符串
if (!key){
alert('请输入关键字');
return false
}
/*追加一条历史*/
historyListArr.push(key);
//保存到localStorage
localStorage.setItem('historyList',JSON.stringify(historyListArr));
//渲染
render();
$('[type="search"]').val('');
});
/*3.点击删除的时候删除对应的历史记录渲染列表*/
$('ul').on('click','a',function () {
let index=$(this).data('index');//拿到自定义属性的下标
historyListArr.splice(index,1);//del
localStorage.setItem('historyList',JSON.stringify(historyListArr));//保存
render();
});
/*4.点击清空的时候清空历史记录渲染列表*/
$('div>a').on('click',function () {
historyListArr=[];//初始化内存里的数据
localStorage.setItem('historyList','');
render();
});
});
</script>
</body>
</html>