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

jQuery嵌套列表过滤:匹配父元素时显示所有子元素

修复嵌套列表过滤的jQuery函数问题

我帮你捋了下这个嵌套列表过滤的问题,核心是你之前的逻辑在处理父元素匹配时,没有强制锁定子元素的显示状态,导致被后续的遍历操作抵消了。咱们直接上修复后的方案:

修复后的完整代码

JavaScript部分

$(document).ready(function() {
  $('#filterInput').on('input', function() {
    const filterText = $(this).val().toLowerCase();
    
    // 先统一隐藏所有列表项,清除之前的过滤状态
    $('.nested-list li').hide();
    
    $('.nested-list li').each(function() {
      const $currentLi = $(this);
      const currentText = $currentLi.text().toLowerCase();
      
      // 判断三个匹配条件:自身匹配、有匹配的子元素、有匹配的父元素
      const isSelfMatch = currentText.includes(filterText);
      const hasMatchingChild = $currentLi.find('li').filter(function() {
        return $(this).text().toLowerCase().includes(filterText);
      }).length > 0;
      const hasMatchingParent = $currentLi.parents('li').filter(function() {
        return $(this).text().toLowerCase().includes(filterText);
      }).length > 0;
      
      // 满足任一条件就显示当前项
      if (isSelfMatch || hasMatchingChild || hasMatchingParent) {
        $currentLi.show();
        
        // 如果当前项是匹配的父元素,强制显示它的所有子元素
        if (isSelfMatch) {
          $currentLi.find('li').show();
        }
      }
    });
  });
});

对应HTML结构示例

<input type="text" id="filterInput" placeholder="输入关键词过滤">
<ul class="nested-list">
  <li>前端开发
    <ul>
      <li>HTML</li>
      <li>CSS</li>
      <li>JavaScript</li>
    </ul>
  </li>
  <li>后端开发
    <ul>
      <li>Node.js</li>
      <li>Python</li>
      <li>Java</li>
    </ul>
  </li>
</ul>

关键修复点说明

  • 统一初始化状态:每次输入时先隐藏所有li,避免之前的过滤残留状态干扰新结果
  • 三重匹配判断:覆盖了三种需要显示的场景:元素自身匹配、包含匹配的子元素、父元素匹配
  • 强制显示子元素:当父元素自身匹配时,主动调用$currentLi.find('li').show(),直接强制显示所有子元素,彻底解决了之前的“抵消”问题

这样修改后,两种逻辑就能正常工作了:子元素匹配时父元素会自动显示,父元素匹配时它的所有子元素也会全部展示出来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:15:47