在做移动端时候,特别是在做搜索功能,不仅会遇到搜索实时检索,还会做到搜索历史记录的功能。
在这里就简单介绍一下搜索历史记录的实现原理。
用的是浏览器自带的 localstorage 保存数组值
数组中最大长度只能为5条(可以自行编辑多少条),每插一条数据都在第一条数据的前面
如果有重复的数据,就把重复的数据删掉再把数据插入到数据的最前面
最新输入搜索的结果总是展示在数据的最前面
话不多说,下面看代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
<title>Title</title>
<style>
html,body{
line-height: 1.5;
color: #333;
background: #fff;
font-family: "Microsoft Yahei", serif
}
.content{
font-size: 0;
}
.content .item{
display: inline-block;
padding: 5px 15px;
background: #f5f5f5;
font-size: 1.2rem;
margin-right: 10px;
color: #333;
border-radius: 4px;
margin-top: 10px;
}
</style>
</head>
<body>
<input type="text" id="search">
<button id="searchBtn" onclick="saveSearch()">搜索</button>
<div class="content" id="content"></div>
</body>
<script>
let searchHistory = [];
const SEARCH_KEY = '__search__';
const SEARCH_MSX_LENGTH = 5;
localStorage.setItem(SEARCH_KEY, JSON.stringify(searchHistory));
/*
* @param arr 数组
* @param val 保存的数值
* @param compare 比较函数
* @param maxLen 数组的最大值
*/
function insertArray(arr, val, compare, maxLen) {
// 先查找数组有没有val 值
const index = arr.findIndex(compare);
// 如果是第一条数据就不做操作
if (index === 0) {
return
}
// 如果有 val值 就先删掉再插入
if (index > 0) {
arr.splice(index, 1)
}
// 没有就直接插入
arr.unshift(val);
// 超过数组的最大数量就把最后一个删掉
if (maxLen && arr.length > maxLen) {
arr.pop()
}
}
function saveSearch() {
let search = trim(document.getElementById('search').value);
if(!search){
console.log('请输入搜索关键字');
return
}
searchHistory.push(search);
let searchHistoryArr = JSON.parse(localStorage.getItem(SEARCH_KEY));
insertArray(
searchHistoryArr,
search,
function compare(item){
return item === search
},
SEARCH_MSX_LENGTH
);
localStorage.setItem(SEARCH_KEY, JSON.stringify(searchHistoryArr));
let searchList = JSON.parse(localStorage.getItem(SEARCH_KEY));
let html = '';
for(let i = 0;i < searchList.length; i++){
html += '<span class="item">' + searchList[i] + '</span>';
}
document.getElementById('content').innerHTML = html
}
// 去处左右空格
function trim(str) {
return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
}
</script>
</html>
在线预览:猛戳这里