簡體   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