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

求助:如何组合多个jQuery筛选器,根据子div的name属性隐藏父级container?

解决jQuery filter()组合筛选container的问题

嘿,别慌!我来帮你搞定这个动态container的筛选问题。你的需求是根据内部.city和.region的name属性,组合筛选并隐藏对应的父级.container,对吧?下面我给你两种常见场景的实现方案,你可以根据自己的实际需求调整:


场景1:筛选同时满足city和region条件的container

比如你想只保留city[name="64"]且region[name="7"]的container,隐藏其他的:

// 定义你的筛选条件
const targetCityName = "64";
const targetRegionName = "7";

// 使用filter()筛选不符合条件的container并隐藏
$('.container').filter(function() {
  // 检查当前container内的city和region的name属性是否都匹配
  const hasMatchingCity = $(this).find('.city').attr('name') === targetCityName;
  const hasMatchingRegion = $(this).find('.region').attr('name') === targetRegionName;
  // 返回false的元素会被筛选掉(也就是我们要隐藏的)
  return !(hasMatchingCity && hasMatchingRegion);
}).hide();

或者反过来,先隐藏所有container,再显示符合条件的,逻辑更直观:

// 先隐藏所有container
$('.container').hide();
// 筛选符合条件的并显示
$('.container').filter(function() {
  const cityName = $(this).find('.city').attr('name');
  const regionName = $(this).find('.region').attr('name');
  return cityName === targetCityName && regionName === targetRegionName;
}).show();

场景2:筛选满足city或region任一条件的container

如果只要container里的city或者region有一个匹配就保留,比如显示city[name="64"]或者region[name="8"]的container,甚至支持多值筛选:

const targetCityNames = ["64", "65"]; // 可设置多个目标城市name
const targetRegionNames = ["7", "8"]; // 可设置多个目标区域name

$('.container').filter(function() {
  const cityName = $(this).find('.city').attr('name');
  const regionName = $(this).find('.region').attr('name');
  // 检查city是否在目标列表,或者region是否在目标列表
  const isMatch = targetCityNames.includes(cityName) || targetRegionNames.includes(regionName);
  // 隐藏不匹配的container
  return !isMatch;
}).hide();

关键细节提醒

  • $(this)在filter()的回调函数里代表当前遍历的.container元素,这样能精准针对每个容器单独检查子元素,不会互相干扰。
  • 如果你的name属性值是数字类型,记得把判断条件里的字符串改成数字(比如=== 64而非=== "64"),避免类型不匹配导致筛选失效。
  • 要是筛选条件是动态变化的(比如用户选择不同的城市/区域),只需要更新目标值或数组,重新执行筛选逻辑就可以了。

内容的提问来源于stack exchange,提问作者Evren Kundakçı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:27:04