繁体   English   中英

复选框和JS过滤项目

[英]Checkbox and Filtering Items with JS

我正在尝试使用复选框构建一组过滤器。

例如,我有:

  • 红色方块
  • 红色圆圈
  • 蓝色方块
  • 蓝色圆圈

并希望能够根据颜色和形状进行过滤。 我有困难。

如果运行本文中的代码,您将看到我的.querySelector()方法未提取'.red'类的所有元素。 它只是更改具有该类名称的第一个元素,而不是更改具有该类名称的每个元素。 如果我使用.querySelectorAll()方法,我也没有运气。

我希望得到的结果是“仅红色”,“仅蓝色”,“仅圆形”和“仅正方形”复选框,并且一次可以激活多个过滤器。

任何帮助表示赞赏。

 const allRedItems = document.querySelector(".red"); const checkBox = document.querySelector('#hide'); checkBox.addEventListener('change', function(e){ if (hide.checked){allRedItems.style.display = "none";} else { allRedItems.style.display = "inline-block"; } }); 
 div { height:100px; width:100px; border:1px solid #ccc; display:inline-block; margin:2rem; } .red { background-color:red; } .blue { background-color:blue; } .square { border-radius:5px; } .circle { border-radius:50%; } 
 <div class="red circle"></div> <div class="red square"></div> <div class="blue circle"></div> <div class="blue square"></div> <br> <input type="checkbox" id="hide"> <label for="hide">Hide All Red Elements</label> 

有关querySelector文档

返回文档中与指定选择器匹配的第一个Element

您正在寻找的功能是querySelectorAll

Element方法querySelectorAll()返回一个静态(非实时)NodeList,它表示与指定选择器组匹配的文档元素的列表。

因为它将返回元素数组而不是单个元素,所以请确保遍历该数组。

 const allRedItems = document.querySelectorAll(".red"); const checkBox = document.querySelector('#hide'); checkBox.addEventListener('change', function(e){ allRedItems.forEach( function(item) { if (hide.checked){ item.style.display = "none"; } else { item.style.display = "inline-block"; } }); }); 
 div { height:100px; width:100px; border:1px solid #ccc; display:inline-block; margin:2rem; } .red { background-color:red; } .blue { background-color:blue; } .square { border-radius:5px; } .circle { border-radius:50%; } 
 <div class="red circle"></div> <div class="red square"></div> <div class="blue circle"></div> <div class="blue square"></div> <br> <input type="checkbox" id="hide"> <label for="hide">Hide All Red Elements</label> 

最后一点,您应该能够基于选定的框构建一个函数来创建查询所需的查询字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM