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

求助:基于多输入值的数组逻辑AND匹配搜索实现(仅JS/jQuery)

实现多输入框AND逻辑搜索方案

没问题,我来帮你搞定这个AND逻辑的搜索功能!你的现有代码已经完成了非空输入值的收集,但还缺少核心的匹配逻辑和结果展示环节,下面是完整的解决方案:

完整JavaScript代码(jQuery版)

$("#search").click(function(){
  // 定义药房数据,注意当前结构是 [Nome, Città, CAP],暂未包含Indirizzo字段
  const pharmacies = [
    ["Vaccaro", "Bagheria", "90011"],
    ["Greco", "Bagheria", "90011"],
    ["Timoneri", "Bagheria", "90011"]
  ];

  // 收集非空的搜索条件,同时记录每个输入对应的字段索引
  const searchFilters = [];
  $('.campi').each(function(index) {
    const inputValue = $(this).val().trim().toLowerCase();
    if (inputValue) {
      searchFilters.push({
        fieldIndex: index,
        value: inputValue
      });
    }
  });

  // 执行AND逻辑匹配:只有满足所有非空条件的药房才会被保留
  const matchedResults = pharmacies.filter(pharmacy => {
    return searchFilters.every(filter => {
      // 特殊处理地址字段:当前pharmacies数组没有地址数据,若用户填了地址则直接不匹配
      if (filter.fieldIndex === 1) {
        return false;
      }
      // 其他字段做不区分大小写的包含匹配(如果需要精确匹配,替换为 === 即可)
      return pharmacy[filter.fieldIndex].toLowerCase().includes(filter.value);
    });
  });

  // 将匹配结果渲染到#result容器中
  const resultContainer = $('#result');
  if (matchedResults.length === 0) {
    resultContainer.html('<p>Nessun farmacia corrispondente trovata.</p>');
  } else {
    let resultHtml = '<ul>';
    matchedResults.forEach(pharmacy => {
      resultHtml += `<li><strong>Nome:</strong> ${pharmacy[0]}, <strong>Città:</strong> ${pharmacy[1]}, <strong>CAP:</strong> ${pharmacy[2]}</li>`;
    });
    resultHtml += '</ul>';
    resultContainer.html(resultHtml);
  }
});

关键逻辑说明

  • AND逻辑实现:用Array.filter()遍历药房数组,结合Array.every()确保每个非空搜索条件都被满足,只有全部符合的药房才会进入结果集。
  • 友好搜索处理:加入trim()去除首尾空格、toLowerCase()实现不区分大小写的搜索,提升用户体验。
  • 地址字段兼容:因为你的pharmacies数组目前没有地址数据,所以如果用户填写了地址,会直接过滤掉所有结果。后续如果补充了地址字段,只需修改pharmacies数组结构,去掉这段特殊判断即可。
  • 结果展示:根据匹配结果数量,动态渲染列表或无结果提示,让用户清晰看到搜索反馈。

优化后的HTML(可选,提升体验)

你可以给输入框添加占位符,让用户更清楚每个输入框的用途:

<input class="campi" id="nome" type="text" name="name" placeholder="Nome farmacia">
<input class="campi" id="indirizzo" type="text" name="address" placeholder="Indirizzo">
<input class="campi" id="città" type="text" name="city" placeholder="Città">
<input class="campi" id="cap" type="text" name="zip" placeholder="CAP">
<button id="search" type="submit">Cerca</button>
<div id="result"></div>

这样修改后,点击搜索按钮就会严格按照AND逻辑执行搜索,只有所有非空输入框的值都匹配对应字段的药房才会被展示出来~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:05:54