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

JavaScript实现路线卡片列表搜索筛选功能异常问题求助

问题核心原因

你的代码存在两处关键错误:

  • 两层循环使用了同名的i变量,内层遍历单元格的i覆盖了用于定位卡片的外层i。你在内层操作routeDetail[i]时,这里的i是单元格的索引(取值范围0~3),永远只会操作前4张卡片;后2张卡片的索引是4、5,从来不会被代码命中设置显示状态,所以一直保持默认显示,这就是你永远只能看到最后2张卡片的直接原因。
  • 筛选逻辑错误:当前逻辑会以最后一个单元格的匹配结果为准,只要最后一个单元格不匹配,就算前面的单元格匹配也会把卡片隐藏。正确逻辑应该是只要任意一个单元格包含搜索值,就保留卡片。

修复后完整代码

const input = document.getElementById('search');
input.addEventListener('keyup', search);

function search() {
  const inputValue = input.value.trim().toLowerCase();
  const routeContainer = document.getElementById('route');
  const routeList = routeContainer.getElementsByClassName('route__filter');

  // 遍历每一张路线卡片
  for(let cardIndex = 0; cardIndex < routeList.length; cardIndex++) {
    const currentCard = routeList[cardIndex];
    const textCells = currentCard.querySelectorAll(".route__parent td.route__text");
    let isMatch = false;

    // 遍历当前卡片的所有可搜索单元格,只要有一个匹配就标记为命中
    for(let cellIndex = 0; cellIndex < textCells.length; cellIndex++) {
      const cellText = textCells[cellIndex].textContent.trim().toLowerCase();
      if (cellText.includes(inputValue)) {
        isMatch = true;
        break; // 已经匹配就不用再查剩下的单元格
      }
    }

    // 根据匹配结果设置卡片显示状态
    currentCard.style.display = isMatch ? "" : "none";
  } 
}
search();

修改点说明

  • 把两层循环的变量名改为语义化的cardIndex(卡片索引)和cellIndex(单元格索引),彻底避免变量冲突
  • 新增isMatch标记位,遍历单元格时只要有一个匹配就标记为命中,避免单个单元格匹配结果覆盖整体判断的问题
  • 统一用textContent代替innerHTML,避免标签特殊字符干扰匹配
  • 新增trim()处理首尾空格,避免输入或内容里的多余空格干扰匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:24:02