You need to enable JavaScript to run this app. jQuery实现点击多类.tax元素按文本内容多条件筛选列表
优惠活动
大模型
产品
解决方案
定价
更多

jQuery实现点击多类.tax元素按文本内容多条件筛选列表

多条件筛选功能实现方案

你现有的代码只支持单个筛选条件生效,选择不同维度筛选项时会互相覆盖,下面是支持多条件同时匹配的实现:

实现思路

每次点击筛选项后,先收集所有当前激活的各维度筛选条件,再遍历所有列表项校验是否同时匹配所有已选维度的规则:

  • 单个维度有激活项时,列表项的对应属性需命中任意一个激活项
  • 单个维度无激活项时,该维度不做限制,直接通过校验

代码实现

JavaScript

$(document).ready(function() {
  // 统一筛选逻辑
  function updateFilterResult() {
    // 收集已激活的价格、分类筛选项
    const selectedPrices = $('.tax.price.active').map(function() {
      return $(this).text().trim();
    }).get();
    const selectedCategories = $('.tax.category.active').map(function() {
      return $(this).text().trim();
    }).get();

    $('.list > .item').each(function() {
      const currentPrice = $(this).find('.price').text().trim();
      const currentCategory = $(this).find('.category').text().trim();
      // 校验各维度匹配状态
      const isPriceMatch = selectedPrices.length === 0 || selectedPrices.includes(currentPrice);
      const isCategoryMatch = selectedCategories.length === 0 || selectedCategories.includes(currentCategory);
      
      $(this).toggleClass('hide', !(isPriceMatch && isCategoryMatch));
    });
  }

  // 绑定所有筛选项点击事件
  $('.tax').on('click', function() {
    $(this).toggleClass('active');
    updateFilterResult();
  });
});

CSS

.list {
  display: flex;
  flex-flow: column;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}
.tax {
  cursor: pointer;
  padding: 3px 6px;
  display: inline-block;
}
.active {
  color: red;
}
.hide {
  display: none;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ul>
  <li class="tax price">Free</li>
  <li class="tax price">$100</li>
</ul>
<ul>
  <li class="tax category">Category 1</li>
  <li class="tax category">Category 2</li>
</ul>
<div class="list">
  <span class="item">
    <span class="category">Category 2</span>
    <span class="price">$100</span>
  </span>
  <span class="item">
    <span class="category">Category 1</span>
    <span class="price">$100</span>
  </span>
  <span class="item">
    <span class="category">Category 1</span>
    <span class="price">Free</span>
  </span>
</div>

支持特性

  • 多维度条件同时生效,同时选中价格和分类时仅显示同时满足两个条件的项
  • 同维度支持多选,同一维度选中多个选项时命中任意一个即可通过校验
  • 无任何选中项时默认显示全部列表项
  • 可扩展性强,后续新增筛选维度仅需新增对应类名的筛选项和列表属性,不用重复写事件逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 12:15:03