js 模糊搜索 关键词高亮显示

<!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>

结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值