/*搜索记录相关*/
//从localStorage获取搜索时间的数组
var hisTime;
//从localStorage获取搜索内容的数组
var hisItem;
//从localStorage获取最早的1个搜索时间
var firstKey;
function init (){
//每次执行都把2个数组置空
hisTime = [];
hisItem = [];
//模拟localStorage本来有的记录
localStorage.setItem("a",12333);
//本函数内的两个for循环用到的变量
for(var i=0;i<localStorage.length;i++){
//alert(typeof(localStorage.key(i)));
if(!isNaN(localStorage.key(i))){
hisItem.push(localStorage.getItem(localStorage.key(i)));
hisTime.push(localStorage.key(i));
}
}
//执行init(),每次清空之前添加的节点
$(".history-search-list").html("");
for(i=0;i<hisItem.length;i++){
$(".history-search-list").prepend(
'<li>'+
'<img src="../img/iconfont-shijian copy.png" />'+
'<span id="history-search-list-span">'+hisItem[i]+'</span>'+
'</li>'
);
}
}
//回车搜索
$("#text").keydown(function(event){
event.preventDefault;
var content = $("#text").val();
if(event.which === 13){
if(content.length == 0){
Toast("请输入字符",2000);
}else{
//页面传参
var searchHtml = $(".search").html();
//搜索内容
localStorage.setItem("content",content);
//行业分类
localStorage.setItem("searchHtml",searchHtml);
//搜索记录
var time = (new Date()).getTime();
//输入的内容localStorage有记录
if($.inArray(content,hisItem)>=0){
for(var j = 0;j<localStorage.length;j++){
if(content==localStorage.getItem(localStorage.key(j))){
localStorage.removeItem(localStorage.key(j));
}
}
localStorage.setItem(time,content);
}
//输入的内容localStorage没有记录
else{
//由于限制了只能有5条记录,所以这里进行判断
if(hisItem.length>4){
firstKey = hisTime[0]
localStorage.removeItem(firstKey);
localStorage.setItem(time,content);
}else{
localStorage.setItem(time,content)
}
}
init();
//去列表
loadsearchListContent(content,cateid,areaid);
return false;
}
}
});
//调用init方法
init();
//清除记录功能
$("#clearStorage").on("touchend",function(){
for(var f = 0;f<hisTime.length;f++){
localStorage.removeItem(hisTime[f]);
}
init();
});
});
<div id="search-content">
<div class="hot-search">
<span>
热门搜索
</span>
</div>
<ul class="hot-search-list" id="hot-search-list">
</ul>
<div class="history-search">
<span>
历史搜索
</span>
</div>
<ul class="history-search-list">
</ul>
<p id="clearStorage">清楚历史搜索</p>
</div>