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

JavaScript实现div多条件筛选 新增城市单选与复选框联动

双维度筛选功能实现方案

先修改HTML部分

原有城市单选按钮缺少必要的属性绑定,先做补全:给每个单选按钮加对应城市class的rel属性,绑定onchange触发事件,再加一个默认选中的「全部城市」选项,和物业类型“无选中=全选”的交互逻辑对齐。
修改后的城市筛选代码:

<h3>所在城市</h3>
<div class="radio"><input type="radio" name="cities" rel="all" checked onchange="change()"> 全部城市</div>
<div class="radio"><input type="radio" name="cities" rel="kyiv" onchange="change()"> 基辅</div>
<div class="radio"><input type="radio" name="cities" rel="lviv" onchange="change()"> 利沃夫</div>
<div class="radio"><input type="radio" name="cities" rel="tokyo" onchange="change()"> 东京</div>

另外给所有待筛选的物业卡片统一加公共classproperty-item,方便统一获取元素,比如示例里的卡片改成:

<div class="property-item lviv hotel">
  <div class="hotel-info">
    <p>BonApart Deluxe Hotel</p>
  </div>
</div>

后续新增其他城市、其他物业类型的卡片时,只要给卡片加上对应class即可(比如基辅的酒店加kyiv hotel,东京的青旅加tokyo hostel)。

替换原有JS逻辑

原来的逻辑只处理了物业类型筛选,新逻辑会独立收集两个维度的筛选规则,只有同时满足两个维度要求的卡片才会展示:

function change() {
  // 收集选中的物业类型,全不选默认展示所有类型
  const typeInputs = Array.from(document.querySelectorAll('.checkbox input'));
  const checkedTypes = typeInputs.filter(i => i.checked).map(i => i.rel);
  const allowTypes = checkedTypes.length ? checkedTypes : ['hotel', 'hostel'];

  // 收集选中的城市,选全部城市默认不限制城市范围
  const checkedCity = document.querySelector('.radio input:checked').rel;
  const allowCities = checkedCity === 'all' ? ['kyiv', 'lviv', 'tokyo'] : [checkedCity];

  // 遍历所有物业卡片,双条件同时匹配才显示
  document.querySelectorAll('.property-item').forEach(item => {
    const isTypeMatch = allowTypes.some(t => item.classList.contains(t));
    const isCityMatch = allowCities.some(c => item.classList.contains(c));
    item.style.display = isTypeMatch && isCityMatch ? 'block' : 'none';
  })
}

// 页面初始化时执行一次筛选
change();

核心逻辑说明

  • 两个筛选维度的规则独立收集,互不干扰,后续要加价格、评分之类的新筛选项,只要按同样逻辑加规则收集、加判断条件即可
  • 保留原有物业类型的交互:两个复选框都不勾选时,展示所有类型的物业
  • 城市筛选默认选「全部城市」,不限制城市范围,选中具体城市后只展示对应城市的物业
  • 最终展示条件用与逻辑判断,必须同时符合选中的物业类型、选中的城市两个要求,卡片才会显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:36:47