本地儲存(localStorage,sessionStorage),cookies(歷史記錄儲存)
阿新 • • 發佈:2018-12-06
特性
- 設定、讀取方便
- 容量較大,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>