下面是操作localStorage的代码:
页面代码:
<input type="search" id="search-input" placeholder="请输入你想比价的商品">
<div class="search-history">
<ul>
<!-- 这里放li标签 -->
</ul>
</div>
<button id="search-btn">搜索</button>
操作localStorage的JS代码
var search = {
//添加localstorage的方法
addlocalStorage : function () {
var that = this;
$('#search-btn').on('click',function(){
var searchContent = $('#search-input').val(); //搜索框里的内容
//判断搜索框里的内容是否为空,如果为空不添加到localstorage不继续下面的操作
if(!searchContent) {
//内容为空
return false;
}
//获取浏览器localstorage中键名为searchHistory中的数据
var historyData = localStorage.getItem('searchHistory');
if(!historyData) {
//因为一开始就没有这个searchHistory键名所以获取到为空,此时将historyData赋值为空数组
historyData = [];
}else {
//不为空,那么键名存在,数据也存在并且是字符串,现在转化为数组
historyData = JSON.parse(historyData);
}
//判断搜索的内容是否重复
if(historyData.indexOf(searchContent) != -1) {
//如果有删除原来的内容,再作为第一个元素添加在数组前
historyData.splice(historyData.indexOf(searchContent),1); //删除
historyData.unshift(searchContent); //添加
}else {
//如果没有,直接作为第一个元素添加在数组前
historyData.unshift(searchContent);
}
//将数据添加到键名为searchHistory中localstorage中的数据,不过又要把数组转成字符串
localStorage.setItem('searchHistory',JSON.stringify(historyData));
//调用查询历史记录的方法
that.queryHistory(); //在这里调用的意思是我搜索后就渲染到页面,可以不加
//清空下拉框里面的数据
$('#search-input').val("");
});
},
//查询localstorage的方法
queryLocalStorage : function(){
//先取出来
var searchData = JSON.parse(localStorage.getItem('searchHistory'));
//循环遍历生成li标签
var liHTML = "";
for(var i=0;i<searchData.length;i++) {
//searchData里面有没有数据
if(searchData[i]) {
var str = '<li>'+ searchData[i] +'</li>';
liHTML += str;
}
}
//在页面上的操作渲染li
//doSometing.......
//给输入框一个成为焦点事件
$('#search-input').on('focus',function(){
$('.search-history ul').html(liHTML);
//再给li一个点击事件
$('.search-history ul li').on('click',function(){
$('#search-input').val($(this).text());
$('.search-history ul').hide();
});
});
}
}
//调用添加localstorage的方法
search.addlocalStorage();
//调用查询localstorage的方法并渲染到页面
search.queryLocalStorage();