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

如何将jQuery实现的标签切换功能改写为原生JavaScript?

Hey there! I totally get where you're coming from—making the switch from jQuery to vanilla JS can feel a bit tricky at first, but breaking down familiar features like tab switching is a great way to build that understanding. Let's walk through how to recreate your tab functionality with plain JavaScript, then break down the key differences between the two approaches.

Full Vanilla JS Implementation

First, here's the complete code that matches your jQuery version's behavior (including the fade-in animation):

<!DOCTYPE html>
<html>
<head>
    <style>
        .tabContent {
            display: none;
            transition: opacity 0.5s ease; /* Adds smooth fade effect */
        }
        #tab1 {
            display: block;
            opacity: 1;
        }
        .tabContainer .current {
            /* Keep your existing highlight styles here */
            font-weight: bold;
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="tabWrapper">
        <ul class="tabContainer">
            <li class="current"><a href="#tab1">Tab 1</a></li>
            <li><a href="#tab2">Tab 2</a></li>
            <li><a href="#tab3">Tab 3</a></li>
        </ul>
        <div id="tab1" class="tabContent">Tab 1 Content</div>
        <div id="tab2" class="tabContent">Tab 2 Content</div>
        <div id="tab3" class="tabContent">Tab 3 Content</div>
    </div>

    <script>
        // Wait for the DOM to be fully loaded (more reliable than setTimeout)
        document.addEventListener('DOMContentLoaded', function() {
            // Grab all tab links
            const tabLinks = document.querySelectorAll('.tabContainer a');
            
            // Add click event listener to each link
            tabLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    // Stop the default link behavior (jumping to the anchor)
                    e.preventDefault();
                    
                    // Handle active tab styling
                    const activeTabLi = this.parentElement;
                    // Add "current" class to the clicked tab's parent li
                    activeTabLi.classList.add('current');
                    // Remove "current" class from all sibling li elements
                    Array.from(activeTabLi.parentElement.children).forEach(li => {
                        if (li !== activeTabLi) {
                            li.classList.remove('current');
                        }
                    });
                    
                    // Handle tab content visibility
                    const activeTabId = this.getAttribute('href');
                    const activeTabContent = document.querySelector(activeTabId);
                    const allTabContents = document.querySelectorAll('.tabContent');
                    
                    // Hide all tab contents first
                    allTabContents.forEach(content => {
                        content.style.display = 'none';
                        content.style.opacity = 0;
                    });
                    
                    // Fade in the active tab content
                    activeTabContent.style.display = 'block';
                    // Trigger a reflow to make the opacity transition work
                    void activeTabContent.offsetWidth;
                    activeTabContent.style.opacity = 1;
                });
            });
        });
    </script>
</body>
</html>

Key Differences Between jQuery and Vanilla JS

Let's break down how this differs from your jQuery code to help you spot patterns:

  • Selectors: jQuery's $() wraps elements in a jQuery object, while vanilla JS uses querySelector()/querySelectorAll() to get raw DOM elements. For collections (like all tab links), you'll loop through them with forEach() (modern browsers support NodeList.forEach directly, but Array.from() helps with older ones).
  • Event Binding: Instead of .click(), we use addEventListener(). This lets you attach multiple listeners to the same element without overwriting existing ones—something jQuery does too, but it's good to see the native way.
  • Class Manipulation: jQuery's .addClass()/.removeClass() maps directly to vanilla JS's classList.add()/classList.remove()—super straightforward once you get used to calling it on the DOM element itself.
  • DOM Traversal: jQuery's .parent()/.siblings() are handy shortcuts, but in vanilla JS we use parentElement and loop through the parent's children to target siblings. It's a bit more verbose, but it gives you clear control over what elements you're targeting.
  • Animation: jQuery's .fadeIn() is a pre-built method, but we used CSS transitions on opacity to mimic the effect here. CSS animations are more performant than JS-based ones, so this is a good practice to adopt.
  • DOM Ready: Instead of a setTimeout (which is unreliable), we use DOMContentLoaded to ensure our code runs only after the DOM is fully parsed—this is the vanilla equivalent of jQuery's $(document).ready().

Tips for Your Vanilla JS Journey

  • Start Tiny: Rewrite small jQuery snippets (like hiding an element on click) first. This builds muscle memory fast.
  • Learn the DOM API: Get comfortable with methods like closest() (great for traversing up the DOM, just like jQuery's .closest()), getAttribute, and classList—they're your new best friends.
  • Lean on CSS: Use CSS for animations, hover states, and layout whenever possible. It's cleaner and faster than doing it all in JS.
  • Check Browser Support: If you need to support older browsers, you might need polyfills for some methods, but modern browsers handle almost all vanilla JS features natively now.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:24:05