请求将指定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
activeTabclass—this ensures only one label is active at a time. - Add active state to clicked label: We explicitly add
activeTabto the clicked element when it's not already active. - Toggle content visibility: We loop through all tab content elements and toggle the
activeTabContentclass, 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
相关产品推荐
相关产品推荐

