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

JS实现点击按钮按textContent筛选控制对应div显隐

原有代码错误说明

filter1 存在的问题

  • getElementsByClassName返回的是包含多个匹配元素的集合(HTMLCollection),不是单个DOM元素,不能直接对集合设置style属性,必须遍历集合内的每个元素单独修改样式
  • 调用getElementsByClassName时类名参数前多余加了.,该方法只需要传入纯类名字符串即可,不需要带CSS选择器前缀
  • 点击分类按钮时没有先隐藏所有水果元素就尝试显示对应分类,会导致之前显示的其他分类元素无法被隐藏

filter2 存在的问题

  • 同样错误地对getElementsByClassName返回的元素集合直接绑定事件、读取属性,集合本身没有onclick、textContent属性
  • 没有给按钮绑定点击触发逻辑,函数不会在点击按钮时自动执行
  • 同样存在直接给元素集合设置style属性的错误
  • 隐藏所有水果的逻辑放在了if判断里,点击非All按钮时无法保证其他分类元素被正确隐藏

推荐通用实现(对应filter2思路,零额外维护成本)

这个方案完全匹配"新增按钮无需修改JS"的需求,后续新增分类时,只需要添加对应文本的按钮、给内容div加上和按钮文本小写一致的类名即可,不需要调整任何JS代码。

<!DOCTYPE html>
<html>
<head>
  <title>筛选功能</title>
  <style type="text/css">
    .btn {
      display: block;
      margin: 4px 0;
      cursor: pointer;
    }
    .fruit {
      display: block;
      margin: 2px 8px;
    }
  </style>
</head>
<body>
  <button class="btn">All</button>
  <button class="btn">Apples</button>
  <button class="btn">Lemons</button>
  <!-- 新增分类按钮示例:<button class="btn">Oranges</button> -->
  
  <section>
    <div class="apples fruit">Green Apple</div>
    <div class="apples fruit">Red Apple</div>
    <div class="lemons fruit">Yellow Lemon</div>
    <!-- 新增分类内容示例:<div class="oranges fruit">Navel Orange</div> -->
  </section>

  <script>
    window.onload = function() {
      // 获取所有筛选按钮和内容元素
      const allButtons = document.querySelectorAll(".btn");
      const allFruits = document.querySelectorAll(".fruit");

      // 统一给所有按钮绑定点击事件
      allButtons.forEach(btn => {
        btn.onclick = function() {
          // 拿到当前按钮的文本,转小写作为筛选类名
          const filterType = this.textContent.trim().toLowerCase();
          
          // 第一步:先隐藏所有内容
          allFruits.forEach(item => item.style.display = "none");

          // 第二步:显示对应分类的内容
          if (filterType === "all") {
            allFruits.forEach(item => item.style.display = "block");
          } else {
            document.querySelectorAll(`.${filterType}`).forEach(item => item.style.display = "block");
          }
        }
      })
    }
  </script>
</body>
</html>

修复后的filter1实现(按id绑定事件)

如果需要保留按id绑定的写法,修复所有错误后的代码如下,注意这个方案每新增一个按钮就要新增一段对应的事件绑定代码,适合按钮数量固定的场景:

<!DOCTYPE html>
<html>
<head>
  <title>筛选功能</title>
  <style type="text/css">
    .btn {
      display: block;
      margin: 4px 0;
      cursor: pointer;
    }
    .fruit {
      display: block;
      margin: 2px 8px;
    }
  </style>
</head>
<body onload="filter1()">
  <button id="all" class="btn">All</button>
  <button id="apples" class="btn">Apples</button>
  <button id="lemons" class="btn">Lemons</button>
  
  <section>
    <div class="apples fruit">Green Apple</div>
    <div class="apples fruit">Red Apple</div>
    <div class="lemons fruit">Yellow Lemon</div>
  </section>

  <script>
    function filter1(){
      const fruits = document.getElementsByClassName("fruit");
      
      document.getElementById("all").onclick = function(){
        for(let i = 0; i < fruits.length; i++){
          fruits[i].style.display = "block";
        }
      };
      
      document.getElementById("apples").onclick = function(){
        // 先隐藏所有水果
        for(let i = 0; i < fruits.length; i++){
          fruits[i].style.display = "none";
        }
        // 显示苹果分类,注意类名不要加.
        const apples = document.getElementsByClassName("apples");
        for(let i = 0; i < apples.length; i++){
          apples[i].style.display = "block";
        }
      };
      
      document.getElementById("lemons").onclick = function(){
        for(let i = 0; i < fruits.length; i++){
          fruits[i].style.display = "none";
        }
        const lemons = document.getElementsByClassName("lemons");
        for(let i = 0; i < lemons.length; i++){
          lemons[i].style.display = "block";
        }
      };
    }
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:51:21