本地存储搜索历史
在做搜索之类功能时遇到要把搜索历史存储起来,下次再进入时展示出来;网上找到一段代码,如下:
function saveSearchinfo(key) {
key = key.replace('搜索商品名称', '');
if (listHistoryArrayObj.indexOf(key) < 0 && key != '') {
listHistoryArrayObj.splice(0, 0, key);
listHistoryArrayObj.length > 5 ? listHistoryArrayObj.length = 5 : '';
} else if (listHistoryArrayObj.indexOf(key) >= 0 && key != '') {
var chge = listHistoryArrayObj.indexOf(key);
listHistoryArrayObj.splice(chge, 1);
listHistoryArrayObj.splice(0, 0, key);
}
localStorage.setItem('lihs', listHistoryArrayObj);
}
ctrl+c之后不知哪里修改错了没有达到预期的效果,只能自己写一个了,虽然没有这个简洁,总算功能达到了
if(!!localStorage.getItem("searchKeyword")) {
var searchKeywordInfo = JSON.parse(localStorage.getItem("searchKeyword"));
var searchHisArr = new Array();//搜索历史
if(!!localStorage.getItem("SHarr")) {
searchHisArr = JSON.parse(localStorage.getItem("SHarr"));
if(searchHisArr.indexOf(searchKeywordInfo)<0) {//不存在
searchHisArr.push(searchKeywordInfo);
if(searchHisArr.length>10) {
searchHisArr = searchHisArr.splice(1,searchHisArr.length);
}
localStorage.setItem("SHarr",JSON.stringify(searchHisArr));
}else {//存在
var k = searchHisArr.indexOf(searchKeywordInfo);
searchHisArr.splice(k,1);
searchHisArr.push(searchKeywordInfo);
localStorage.setItem("SHarr",JSON.stringify(searchHisArr));
}
}else {
searchHisArr.push(searchKeywordInfo);
localStorage.setItem("SHarr",JSON.stringify(searchHisArr));
}}