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

基于多Data属性的jQuery Div过滤问题:多值属性匹配失效

解决多值data属性过滤失效问题

问题根源

原代码直接将div的data属性完整字符串与filterList中的项做匹配,当data属性是逗号分隔的多值时(如data-one="val1,val2"),完整字符串无法匹配filterList中的单个值,导致过滤失效。

修正步骤

  1. 修复变量名笔误:第一个循环里的filterList.push(dataType);应为filterList.push(dataOne);,避免无效数据进入filterList。
  2. 新增多值匹配工具函数:编写函数判断目标值(单值/逗号分隔多值)是否与filterList存在交集。
  3. 替换原匹配逻辑:用工具函数替代jQuery.inArray判断,兼容多值场景。

完整修正代码

var filterList = [];

// 修复变量名笔误,将dataType改为对应data属性变量
jQuery("#jsonFilters ul#one ul li a.active").each(function() {
  var dataOne = jQuery(this).attr("data-one");
  filterList.push(dataOne);
});

jQuery("#jsonFilters ul#two ul li a.active").each(function() {
  var dataTwo = jQuery(this).attr("data-two");
  filterList.push(dataTwo);
});

jQuery("#jsonFilters ul#three ul li a.active").each(function() {
  var dataThree = jQuery(this).attr("data-three");
  filterList.push(dataThree);
});

jQuery("#jsonFilters ul#four ul li a.active").each(function() {
  var dataFour = jQuery(this).attr("data-four");
  filterList.push(dataFour);
});

jQuery("#jsonFilters ul#five ul li a.active").each(function() {
  var dataFive = jQuery(this).attr("data-five");
  filterList.push(dataFive);
});

// 工具函数:判断目标值(单值/多值)是否与filterList有交集
function hasMatch(targetValue, filterArray) {
  if (!targetValue) return false;
  // 分割多值并去除空格,兼容"val1, val2"格式
  var targetArray = targetValue.split(",").map(item => item.trim());
  // 检查是否有至少一个值在过滤列表中
  return targetArray.some(item => filterArray.includes(item));
}

if (filterList.length == 0) {
  jQuery('.div').removeClass('hidden').fadeIn();
  console.log('No Filters');
} else {
  jQuery('.div').each(function() {
    var $this = jQuery(this);
    var offeringOne = $this.attr('data-one');
    var offeringTwo = $this.attr('data-two');
    var offeringThree = $this.attr('data-three');
    var offeringFour = $this.attr('data-four');
    var offeringFive = $this.attr('data-five');

    // 使用工具函数替换原匹配逻辑
    var matchOne = hasMatch(offeringOne, filterList);
    var matchTwo = hasMatch(offeringTwo, filterList);
    var matchThree = hasMatch(offeringThree, filterList);
    var matchFour = hasMatch(offeringFour, filterList);
    var matchFive = hasMatch(offeringFive, filterList);

    if (matchOne && matchTwo && matchThree && matchFour && matchFive) {
      $this.fadeIn('slow');
    } else {
      $this.hide();
    }
  });
}

补充说明

  • 工具函数兼容带空格的逗号分隔场景(如"val1, val2")。
  • 修正了原代码未声明变量的问题,避免全局变量污染。
  • 保留原逻辑中五个data属性都需匹配的规则,若需改为“任一匹配”,只需将&&替换为||即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:08:27