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

如何用jQuery/JavaScript实现输入重复关键词时弹窗提示(关键词来自JSON文件)

实现输入框重复名称/词汇检测并弹出提示

没问题,我来帮你搞定这个需求!下面是结合你给出的HTML结构,使用jQuery完成重复名称检测和提示的完整方案:

1. 整理后的基础HTML结构

<div class="container">
  <div class="card">
    <div class="col-md-12" style="padding-top: 10px;padding-bottom: 10px;">
      <div class="form-group">
        <input type="text" id="medicineSearchBar" class="form-control" placeholder="Search...">
      </div>
      <ul class="list-group" id="result"></ul>
      <ul style="width:100%; max-height:300px; overflow-y: scroll;" id="li-psearch" class="dropdown-menu" role="menu" aria-labelledby="menu1">
        <li role="presentation" class="divider-search"></li>
      </ul>
    </div>
  </div>
</div>

2. jQuery核心实现代码

// 存储JSON中重复的名称集合
let duplicateTerms = new Set();

$(document).ready(function() {
  // 第一步:加载JSON文件并提取重复项
  $.getJSON('your-data.json', function(data) {
    // 统计每个名称的出现次数
    const termCount = {};
    data.forEach(item => {
      // 假设JSON中存储名称的字段是"name",可根据实际结构修改
      const term = item.name.trim().toLowerCase();
      termCount[term] = (termCount[term] || 0) + 1;
    });

    // 筛选出现次数>1的名称,存入集合
    for (const term in termCount) {
      if (termCount[term] > 1) {
        duplicateTerms.add(term);
      }
    }
  });

  // 第二步:监听输入框输入事件,实时检测
  $('#medicineSearchBar').on('input', function() {
    const inputVal = $(this).val().trim().toLowerCase();
    // 输入内容非空且属于重复项时弹出提示
    if (inputVal && duplicateTerms.has(inputVal)) {
      // 这里用原生alert,也可以替换为Bootstrap Toast/自定义模态框
      alert(`提示:"${inputVal}" 是重复的名称/词汇!`);
    }
  });
});

3. 示例JSON文件结构(your-data.json)

[
  {"id": 1, "name": "阿莫西林"},
  {"id": 2, "name": "布洛芬"},
  {"id": 3, "name": "阿莫西林"},
  {"id": 4, "name": "头孢克肟"},
  {"id": 5, "name": "布洛芬"}
]

关键细节说明

  • 字段适配:如果你的JSON中存储名称的字段不是name,记得修改代码里的item.name为实际字段
  • 大小写兼容:代码把输入内容和JSON名称统一转成小写,避免大小写差异导致的检测遗漏
  • 提示优化:原生alert比较基础,你可以替换为更友好的自定义提示组件(比如Bootstrap的Toast),提升用户体验
  • 性能保障:仅在页面加载时处理一次JSON数据,后续检测直接使用集合的has方法,效率很高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:40:00