<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.tip {
display: flex;
}
.list span {
padding: 5px 10px;
display: inline-block;
margin-right: 5px;
background-color: #eee;
border-radius: 3px;
}
</style>
</head>
<body>
<input type="text"><button>搜索</button>
<div class="tip">
<p>最近搜索</p>
<p>删除</p>
</div>
<div class="list">
<span>笔记本</span>
<span>键盘</span>
<span>笔记本</span>
<span>鼠标</span>
</div>
<script>
var inp = document.querySelector('input');
var btn = document.querySelector('button');
//先获取 key的名字叫list
var str = localStorage.getItem('list');
//声明一个数组 不给值
var arr;
if (str === null) {//如果localStorage里面没有存东西
arr = [];//就让arr=空数组
} else {//否则
arr = JSON.parse(str)//arr=在localStorage里面获取到的数组
}
//封装渲染页面的函数
function render(data) {
var str = '';
for (var i = 0; i < data.length; i++) {
str += `<span>${data[i]}</span>`;
}
document.querySelector('.list').innerHTML = str;
}
render(arr);
//给input绑定单击事件
btn.onclick = function () {
var val = inp.value;
if (val !== '') {
if (arr.indexOf(val) === -1) {
arr.unshift(val);
} else {
var index = arr.indexOf(val);
arr.splice(index, 1);
arr.unshift(val);
}
render(arr);
localStorage.setItem('list', JSON.stringify(arr));
inp.value = '';
}
}
</script>
</body>
</html>
本文使用原生js实现一个简易的历史搜索功能,供前端初学者作参考