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

如何用单个函数区分同class按钮并实现内容切换?

解决方案:统一处理多按钮的页面切换逻辑

核心优化思路

用数据属性(data-*)给按钮绑定对应目标页面的标识,再通过单个事件监听器处理所有按钮的点击,无需为每个按钮单独编写函数。

优化后的完整代码

<style>
  .hidden {
    display: none;
  }
</style>
<body>
  <header>
    <!-- 给每个按钮添加data-target属性,值对应目标页面的类名 -->
    <button class="nav-link" data-target="home-page">Home</button>
    <button class="nav-link" data-target="about-page">About</button>
    <!-- 新增按钮直接沿用该结构即可,无需修改JS代码 -->
    <button class="nav-link" data-target="contact-page">Contact</button>
  </header>
  <main>
    <h1 class="main-content home-page hidden">This is the Home Page</h1>
    <h1 class="main-content about-page hidden">This is the About Page</h1>
    <h1 class="main-content contact-page hidden">This is the Contact Page</h1>
  </main>
  <script>
    // 获取所有内容元素和导航父容器
    const mainContent = document.querySelectorAll('.main-content');
    const navHeader = document.querySelector('header');

    // 统一处理页面切换的函数
    const handlePageSwitch = (e) => {
      // 仅处理.nav-link类按钮的点击事件
      if (!e.target.classList.contains('nav-link')) return;
      
      // 获取当前按钮对应的目标页面类名
      const targetPageClass = e.target.dataset.target;
      
      // 先隐藏所有内容页
      mainContent.forEach(content => content.classList.add('hidden'));
      // 再显示目标内容页
      document.querySelector(`.${targetPageClass}`).classList.remove('hidden');
    };

    // 给父容器绑定一次事件监听器,所有子按钮点击都会触发
    navHeader.addEventListener('click', handlePageSwitch);
  </script>
</body>

关键优化点

  • 数据属性关联关系:通过data-target直接建立按钮与目标页面的绑定,新增按钮时只需添加对应属性和页面元素,无需改动JS逻辑。
  • 事件委托机制:将监听器绑定到按钮的父元素(header),而非每个按钮单独绑定,既减少内存占用,新增按钮也能自动生效。
  • 统一逻辑复用:单个函数完成“隐藏全部→显示目标”的流程,彻底避免重复代码。

内容的提问来源于stack exchange,提问作者Taylor Remund

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:50:37