index.html
<!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>
</ul>
<script src="jquery.min.js"></script>
<script>
$(function () {
//先看本地存储的historyList
//存储的是json字符串
var historyListJson=localStorage.getItem('historyList') || '[]';
//把json字符串格式转换成json对象
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();
//属性选择器
$('[type="button"]').on('click',function(){
var key=$('[type="search"]').val();
if(!key){
alert("请输入关键字");
return false;
}
historyListArr.push(key);
//要把这个数组转换成json格式的字符串
localStorage.setItem('historyList',JSON.stringify(historyListArr));
render();
$('[type="search"]').val('');
});
//点击删除一个
$("ul").on('click','a',function(){
var index=$(this).data("index");
historyListArr.splice(index,1);
localStorage.setItem('historyList',JSON.stringify(historyListArr));
render();
});
//点击全删
$("div a").on("click",function(){
historyListArr=[];
//清空
//慎用
//localStorage.clear();
localStorage.setItem("historyList",'');
render();
});
});
</script>
</body>
</html>