如何在W3Schools标签页中添加显示全部内容的‘Everything’标签?
Solution: Add an "Everything" Tab to Show All Content
Got it, let's get this sorted for you! Adding an "Everything" tab that displays all your existing tab content without duplicating any HTML is straightforward—we just need a small adjustment to your openCity function and one extra button.
Modified Full Code
First, here's the complete working code with the new tab included:
HTML
<div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> <!-- New "Everything" tab button --> <button class="tablinks" onclick="openCity(event, 'Everything')">Everything</button> </div> <!-- Tab content (no changes needed here!) --> <div id="London" class="tabcontent"> <h3>London</h3> <p>London is the capital city of England.</p> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div>
JavaScript
function openCity(evt, cityName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" tabcontent = document.getElementsByClassName("tabcontent"); // Handle "Everything" case first if (cityName === "Everything") { // Show all tab content elements for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "block"; } } else { // Original logic: hide all tabs, then show the selected one for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } document.getElementById(cityName).style.display = "block"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Add an "active" class to the button that opened the tab evt.currentTarget.className += " active"; }
Key Changes Explained
- Added the "Everything" button: We just inserted a new button in the
.tabcontainer, pointing to our modified function with'Everything'as the city name parameter. - Updated the
openCityfunction:- We added a conditional check for when
cityNameis'Everything'—instead of hiding all tabs, we loop through every.tabcontentelement and set itsdisplaytoblockto show everything. - For all other tabs, we keep your original logic intact (hide all, show the selected one).
- The active button styling logic works the same way for all tabs, so the "Everything" button will highlight when clicked just like the others.
- We added a conditional check for when
This way, you don't have to duplicate any of your existing content—we're just reusing the HTML you already have!
内容的提问来源于stack exchange,提问作者Himanshu Yadav
相关产品推荐
相关产品推荐

