You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现输入文本匹配标题内容并包裹高亮span标签?

实现标题文本的大小写不敏感全局高亮

直接上解决方案,核心是用正则表达式的全局+大小写不敏感标志配合replace(),同时避免重复嵌套高亮标签,处理空输入的重置逻辑:

完整代码示例

<!-- HTML结构 -->
<input type="text" id="searchInput" placeholder="输入关键词高亮">
<h2 class="title">Hello World! Welcome to the World of Code</h2>
<h3 class="title">The WORLD is full of surprises</h3>

<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>

<script>
// 预先保存每个标题的原始文本,防止多次替换导致span嵌套混乱
const originalTitles = Array.from(document.querySelectorAll('.title')).map(el => el.textContent);

document.getElementById('searchInput').addEventListener('input', function(e) {
  const keyword = e.target.value.trim();
  const titles = document.querySelectorAll('.title');

  titles.forEach((title, index) => {
    if (!keyword) {
      // 输入为空时恢复标题原始内容
      title.innerHTML = originalTitles[index];
      return;
    }

    // 创建全局匹配+大小写不敏感的正则表达式
    const regex = new RegExp(keyword, 'gi');
    // 将所有匹配内容替换为带highlight类的span标签
    title.innerHTML = originalTitles[index].replace(regex, match => `<span class="highlight">${match}</span>`);
  });
});
</script>

关键细节说明

  • 提前存储原始文本:避免多次输入操作后,高亮标签被重复嵌套,导致HTML结构混乱
  • 正则gi标志:g确保匹配所有符合条件的文本实例,i忽略大小写,直接解决你遇到的两个局限
  • 实时input监听:用户输入过程中立刻触发高亮更新,交互更流畅
  • 空输入重置:清空关键词时自动恢复标题原始状态,避免残留高亮标记

内容的提问来源于stack exchange,提问作者MeltingDog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:22:04