<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>auto complete</title>
<style>
.blue {
color: rgb(0, 136, 255);
}
li {
list-style: none;
}
</style>
</head>
<body>
<input class="province" type="text">
<section>
<ul class="container"></ul>
</section>
</body>
<script>
function debounce(fn, timeout = 300) {
let t;
return (...args) => {
if (t) {
clearTimeout(t);
}
t = setTimeout(() => {
fn.apply(fn, args);
}, timeout);
}
}
function getInputResult(data, value) {
const reg = new RegExp(`\(${value}\)`);
const search = data.reduce((res, cur) => {
if (reg.test(cur)) {
const match = RegExp.$1;
res.push(`<li>${cur.replace(match, '<span class="blue">$&</span>')}</li>`);
}
return res;
}, []);
return search;
}
function getAllVal(data){
return data.reduce((res, cur) => {
res.push(`<li>${cur}</li>`);
return res;
}, []).join('');
}
const data = ["广州白云区", "白云机场", "广州越秀区", "广州荔湾区", "广州增城", "广州天河区"];
const container = document.querySelector('.container');
const allValue= getAllVal(data);
container.innerHTML = allValue;
const cache = new Map();
document.querySelector('.province').addEventListener('input', debounce(e => {
const val = e.target.value;
let res;
if(!val){
res = allValue;
}else if(cache.has(val)){
res = cache.get(val);
}else{
res = getInputResult(data, val).join('');
cache.set(val, res);
}
container.innerHTML = res ? res : '暂无数据';
}))
</script>
</html>
结果: