JavaScript示例,用于根据多个复选框条件过滤数组。
以下是使用JavaScript根据多个复选框条件过滤数组的代码−
例如
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Filter an array depending on multiple checkbox conditions</h1> <div class="sample">[22,10,50,30,90,33,80,75,33,99,150,105]</div> <div class="result"></div> <br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should be greater than 50<br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 5<br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 3<br /> <h3>tick the above checkbox to apply filter to the array above</h3> <script> let resEle = document.querySelector(".result"); let checkEle = document.querySelectorAll(".check"); let arr = [22, 10, 50, 30, 90, 33, 80, 75, 33, 99, 150, 105]; let resArr = arr; function filterArr() { checkEle.forEach((item, index) => { if (item.checked && index == 0) { resArr = resArr.filter((num) => num > 50); resEle.innerHTML = resArr; } else if (item.checked && index == 1) { resArr = resArr.filter((num) => num % 5 == 0); resEle.innerHTML = resArr; } else if (item.checked && index == 2) resArr = resArr.filter((num) => num % 3 == 0); resEle.innerHTML = resArr; }); } </script> </body> </html>
输出
以上代码会产生以下输出−
勾选一些复选框−
广告