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

请求将指定jQuery标签切换代码转换为VanillaJS代码

Converting jQuery Tab Switching to Vanilla JS

Your current Vanilla JS code is missing a few key pieces that the original jQuery implementation handles. Let's fix that and replicate the exact behavior:

Corrected Vanilla JS Code

// Get all tab labels and tab content elements
const tabLabels = document.querySelectorAll('.tabLabel');
const tabs = document.querySelectorAll('.tab');

// Attach click event listener to each tab label
tabLabels.forEach(tabLabel => {
  tabLabel.addEventListener('click', function() {
    // Exit early if the clicked label is already active
    if (this.classList.contains('activeTab')) {
      return;
    }

    // Remove active class from all tab labels
    tabLabels.forEach(label => label.classList.remove('activeTab'));

    // Add active class to the clicked label
    this.classList.add('activeTab');

    // Toggle the active content class on all tab elements
    tabs.forEach(tab => tab.classList.toggle('activeTabContent'));
  });
});

Key Fixes & Explanations

Let's break down what this code does and how it addresses the gaps in your original attempt:

  • Select tab content elements: We added const tabs = document.querySelectorAll('.tab') to target the content panels, which your code was missing entirely.
  • Exit early for active labels: If the clicked label is already active, we do nothing (matching the original jQuery logic).
  • Clear active state from all labels: Instead of only modifying the clicked label, we loop through all labels to remove the activeTab class—this ensures only one label is active at a time.
  • Add active state to clicked label: We explicitly add activeTab to the clicked element when it's not already active.
  • Toggle content visibility: We loop through all tab content elements and toggle the activeTabContent class, just like the original jQuery $('.tab').toggleClass('activeTabContent') call.

Note: If you need to support older browsers that don't have NodeList.forEach, you can wrap tabLabels and tabs with Array.from() (like you did in your original code) to convert them to arrays first.

内容的提问来源于stack exchange,提问作者cpt-crunchy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:11:27