基于JavaScript实现多维度产品筛选:AND/OR逻辑的应用

基于JavaScript实现多维度产品筛选:AND/OR逻辑的应用

本教程详细阐述了如何使用JavaScript实现多维度产品筛选功能,解决了传统筛选器在处理不同类型条件(如颜色和尺寸)时,如何灵活应用“AND”和“OR”逻辑的挑战。通过分离管理不同维度的筛选条件,并根据用户选择的组合动态调整筛选规则,确保产品列表能够精确响应用户的复杂查询,从而提升用户体验和数据展示的准确性。

1. 动态筛选概述与挑战

在Web应用中,尤其是在电子商务或数据展示平台,动态筛选是提升用户体验的关键功能。用户通过选择不同的筛选条件(如颜色、尺寸、品牌等),实时查看符合要求的产品或数据。然而,当涉及到多个筛选维度时,如何正确处理它们之间的逻辑关系(“AND”或“OR”)是一个常见的挑战。例如,用户可能希望看到“红色”或“蓝色”的产品(OR关系),但当同时选择“红色”和“小尺寸”时,则可能希望看到既是“红色”又是“小尺寸”的产品(AND关系)。

本教程将聚焦于解决这一问题,通过一个产品筛选的实例,演示如何使用JavaScript实现灵活的多维度筛选逻辑。

2. html 结构准备

为了实现多维度筛选,我们需要清晰地定义筛选器和可筛选的产品项。每个筛选器组(如颜色、尺寸)应有独立的标识,同时每个产品项需要包含其对应的属性信息。

<!DOCTYPE html> <html lang="zh-CN"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>多维度产品筛选</title>     <style>         body { font-family: Arial, sans-serif; margin: 20px; }         .Filter-group { margin-bottom: 15px; border: 1px solid #eee; padding: 10px; border-radius: 5px; }         .filter-group h3 { margin-top: 0; color: #333; }         label { display: block; margin-bottom: 5px; }         .filterable {             border: 1px solid #ddd;             padding: 10px;             margin-bottom: 10px;             background-color: #f9f9f9;             border-radius: 4px;         }         .filterable h1 { margin-top: 0; font-size: 1.5em; }     </style> </head> <body>      <div class="filter-group">         <h3>颜色</h3>         <label><input type="checkbox" class="filter-checkbox color-checkbox" value="red">红色</label>         <label><input type="checkbox" class="filter-checkbox color-checkbox" value="green">绿色</label>         <label><input type="checkbox" class="filter-checkbox color-checkbox" value="blue">蓝色</label>     </div>      <div class="filter-group">         <h3>尺寸</h3>         <label><input type="checkbox" class="filter-checkbox size-checkbox" value="small">小型</label>         <label><input type="checkbox" class="filter-checkbox size-checkbox" value="medium">中型</label>         <label><input type="checkbox" class="filter-checkbox size-checkbox" value="large">大型</label>     </div>      <h1>筛选结果</h1>     <div class="filterable" data-attributes="blue large">产品 A</div>     <div class="filterable" data-attributes="green small">产品 B</div>     <div class="filterable" data-attributes="red medium">产品 C</div>     <div class="filterable" data-attributes="red large">产品 D</div>      <script src="script.js"></script> </body> </html>

关键点:

立即学习Java免费学习笔记(深入)”;

  • 筛选器复选框: 每个复选框都带有 filter-checkbox 类用于通用选择,同时附加 color-checkbox 或 size-checkbox 类来区分筛选维度。value 属性存储了筛选的具体值。
  • 可筛选产品项: 每个产品项使用 filterable 类标识,并通过 data-attributes 属性存储其颜色和尺寸信息。例如,data-attributes=”blue large” 表示该产品是蓝色且大型的。这里我们假设 data-attributes 的第一个值是颜色,第二个值是尺寸,且它们之间用空格分隔。

3. JavaScript 核心筛选逻辑

我们将编写 updateFilter 函数来处理筛选逻辑。这个函数会在任何筛选复选框状态改变时被调用。

// script.js const filterCheckboxes = document.querySelectorAll('.filter-checkbox'); const colorCheckboxes = document.querySelectorAll('.color-checkbox'); const sizeCheckboxes = document.querySelectorAll('.size-checkbox'); const filterables = document.querySelectorAll('.filterable');  /**  * 更新产品显示状态的函数  */ function updateFilter() {     // 1. 获取当前选中的颜色和尺寸筛选值     const colorChecked = Array.from(colorCheckboxes)         .filter(checkbox => checkbox.checked)         .map(checkbox => checkbox.value);      const sizeChecked = Array.from(sizeCheckboxes)         .filter(checkbox => checkbox.checked)         .map(checkbox => checkbox.value);      // 2. 如果没有任何筛选条件被选中,则显示所有产品     if (!(colorChecked.Length || sizeChecked.length)) {         filterables.forEach(filterable => {             filterable.style.display = 'block';         });         return; // 结束函数执行     }      // 3. 遍历所有可筛选产品项,根据筛选条件决定其显示状态     filterables.forEach(filterable => {         // 从 data-attributes 中解析产品的颜色和尺寸         // 假设 data-attributes 格式为 "颜色 尺寸"         const attributes = filterable.dataset.attributes.split(' ');         const productColor = attributes[0];         const productSize = attributes[1];          let shouldDisplay = false; // 默认不显示          // 3.1. 如果同时选择了颜色和尺寸筛选器 (AND 逻辑)         if (colorChecked.length >= 1 && sizeChecked.length >= 1) {             // 产品必须同时满足选中的颜色和选中的尺寸             shouldDisplay = colorChecked.includes(productColor) && sizeChecked.includes(productSize);         }         // 3.2. 如果只选择了颜色筛选器 或 只选择了尺寸筛选器 (OR 逻辑)         else {             // 产品满足任意一个选中的颜色 或 任意一个选中的尺寸即可             shouldDisplay = colorChecked.includes(productColor) || sizeChecked.includes(productSize);         }          // 根据 shouldDisplay 决定产品是否可见         filterable.style.display = shouldDisplay ? 'block' : 'none';     }); }  // 4. 为所有筛选复选框添加 change 事件监听器 filterCheckboxes.forEach(checkbox => {     checkbox.addEventListener('change', updateFilter); });  // 5. 页面加载时执行一次筛选,以反映初始状态 updateFilter();

代码解析:

  1. 获取选中值: 通过 querySelectorAll 获取不同类别的复选框,并使用 Array.from、filter 和 map 组合,高效地提取出当前所有被选中的颜色和尺寸值。
  2. 无筛选条件处理: 如果 colorChecked 和 sizeChecked 数组都为空(即没有任何筛选器被选中),则遍历所有产品,将它们全部显示出来。
  3. 核心筛选逻辑:
    • 遍历每个 filterable 元素。
    • 解析 data-attributes 属性,获取产品的颜色和尺寸。
    • AND 逻辑: 当 colorChecked.length >= 1 且 sizeChecked.length >= 1 时,表示用户同时激活了颜色和尺寸两种筛选。此时,只有当产品的颜色同时在 colorChecked 数组中且尺寸同时在 sizeChecked 数组中时,产品才会被显示。
    • OR 逻辑: 当只有颜色筛选器被选中 (colorChecked.length >= 1) 或只有尺寸筛选器被选中 (sizeChecked.length >= 1) 时,产品只要满足任一选中的颜色或尺寸即可显示。
  4. 事件监听: 为所有 filter-checkbox 添加 change 事件监听器,确保每次复选框状态改变时都能触发 updateFilter 函数。
  5. 初始化: 在脚本加载完成后立即调用 updateFilter() 一次,以确保页面加载时,产品列表能根据默认的复选框状态正确显示。

4. 注意事项与优化

  • *`data-属性的格式约定:** 当前实现依赖于data-attributes=”颜色 尺寸”这种固定的顺序和分隔符。如果属性顺序不固定或有更多维度,这种方式会变得脆弱。更健壮的做法是使用独立的data-color=”blue”和data-size=”large”属性,或者将属性值存储为 json 字符串,例如data-attributes='{“color”: “blue”, “size”: “large”}’`,然后在 JavaScript 中解析。
  • 多维度扩展: 如果未来需要增加更多筛选维度(如品牌、材质),可以仿照颜色和尺寸的模式,为新维度添加独立的复选框类和获取选中值的逻辑。核心的筛选循环内部,需要增加更多的 if/else if 或更复杂的逻辑来处理不同维度组合下的 AND/OR 关系。
  • 性能考量: 对于包含成千上万个产品项的大型列表,每次筛选都遍历所有 dom 元素并修改 style.display 可能会引起性能问题。在这种情况下,可以考虑以下优化:
    • 虚拟滚动/分页: 只渲染当前可见的产品项。
    • 数据驱动渲染: 将产品数据存储在 JavaScript 数组中,筛选时操作数组,然后只重新渲染符合条件的部分。
    • css 类切换: 预定义 display: none; 和 display: block; 的 CSS 类,通过添加/移除类来控制显示,而不是直接修改 style 属性。
  • 用户体验:
    • 清除筛选按钮: 提供一个按钮,一键清除所有选中的筛选条件。
    • 筛选结果反馈: 明确显示当前有多少产品符合筛选条件。
    • 加载指示器: 对于复杂或耗时的筛选操作,显示加载动画。

5. 总结

本教程提供了一个实用的 JavaScript 解决方案,用于实现多维度产品筛选功能,并灵活处理不同筛选维度之间的“AND”和“OR”逻辑。通过清晰的 HTML 结构、分离的筛选器管理以及核心的条件判断逻辑,我们可以构建出响应迅速且用户友好的筛选界面。在实际项目中,应根据具体需求和数据规模,进一步考虑代码的健壮性、可扩展性和性能优化

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享