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

jQuery新手求助:如何通过按钮切换/增删.hide类

问题描述

我是jQuery新手,课堂作业要求实现类的切换、添加或移除功能。希望点击对应按钮时,移除目标div的.hide类使其显示,再次点击时重新添加该类隐藏div,目前不知如何实现,附上我的代码,恳请建议。

原代码

CSS

@charset "utf-8";
/* CSS Document */

* {
    padding: 0;
    
}

@import url('https://fonts.googleapis.com/css2?family=Fira+Sans&family=PT+Serif&display=swap');

#hfix {
    width: 20%;
    
}

nav {
    grid-area: nav;
    display: flex;
    background-color: #232770;
top: 0;
    flex-direction: row;
    
}

nav ul {
    list-style-type:none;
    display: flex;
flex-direction: row;
    flex-wrap: wrap;
    
    
}
nav ul li {
    margin: 3px 40px;
    
    
}

nav li a {
    text-decoration: none;
    color:#C2C4F0;
}

nav li a:hover {
    color:#FFFCFC;
}
body {
    background-color:#ECECEC;
    width: 100%;
}
footer {
    grid-area: footer;
    background-color: #232770;
    color:#C2C4F0;
    text-align:center;
    height: 50px;
}

footer p {
    padding-top: 15px;
}
/* for when there isn't enough content to put the footer on the bottom */
#footerfix {
    bottom: 0;
    position: absolute;
    width: 100%;
}

main {
    grid-area: main;
    margin-bottom: 50px;
}

main p {
    padding-left: 100px;
    padding-right: 100px;   
    font-family: 'PT Serif', serif ;
    font-size: 30px;
    text-align: justify;
     display: block;
  margin-left: auto;
  margin-right: auto;
    
}

cite {
    padding-left: 100px;
    text-align: justify;
      display: block;
  margin-left: auto;
  margin-right: auto;
}

h1 {
    font-family: 'Fira Sans', sans-serif;
    font-size: 56px;
    text-align: center;
}

h2 {
    font-family: 'Fira Sans', sans-serif;
    font-size: 40px;
    text-align: center;
}

h3 {
    font-family:'Fira Sans', sans-serif;
    font-size: 30px;
    text-align: center;
}

#fact img {
    height: 400px;
    align-items: center;
     display: block;
  margin-left: auto;
  margin-right: auto;
}


.hide {
    display: none;
    
}

.BestGame {
    
}

.BestSeries {
    
}

.FirstGame {
    
}
.BestConsole {
    
}

.iconic{
    
}

#buttons {
    text-align: center;
        display: block;
  margin-left: auto;
  margin-right: auto;
}
#buttons button {
    margin: 5px;
    padding: 5px;
    font-size: 15px;
}

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>5 Facts about Video Games</title>
<link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <nav>
    <ul>
        <li><a href="../../index.html">Back to Home</a></li>
    <li><a href="../../Project.html">Back to Projects</a></li>
        </ul>
    
    </nav>

<body>
    <main>
    
    <section id="fact">
        <h1>Did You Know?</h1>
        <div id="buttons">
        
        <button class="BestGame">Top Selling Game</button>
            <button class="BestSeries">Top Selling Series</button>
            <button class="FirstGame">First Game</button>
            <button class="BestSeries">Best Selling Console</button>
            <button class="iconic">Iconic Characters</button>
        
        </div>
        <div class="BestGame"><img src="images/minecraft.jpg" alt="Minecraft">
    <h2>The Top Selling Game is Minecraft</h2>
        <p>Minecraft is the top selling game with 300mil sales, followed by Grand Theft Auto V with 190mil sales, and then Tetris with 100mil sales.</p>
            <cite>https://en.wikipedia.org/wiki/List_of_best-selling_video_games</cite></div>
    
        <div class="BestSeries hide"><img src="images/Mario.jpg" alt="Mario and Luigi" >
        <h2>The Best Selling Game Series is Mario</h2>
        <p>Mario has a total of 823mil+ sales, followed by Tetris with 495mil sales, then Pokemon with 480mil</p>
        <cite >https://en.wikipedia.org/wiki/List_of_best-selling_video_game_franchises</cite></div>
    
        <div class="FirstGame hide"><img src="images/tennis.jpg" alt="Tennis for Two" >
        <h2>The First Game Ever Made Was Tennis for Two</h2>
        <p>Created by Physicist William Higinbotham in October of 1958! The game is a simple tennis game, similiar to Pong. Players would used knobs to adjust the angles of the ball and a button to hit the ball to the other player</p>
<cite >https://www.aps.org/publications/apsnews/200810/physicshistory.cfm#:~:text=Higinbotham%20made%20some%20drawings%2C%20and,the%20game%20Tennis%20for%20Two.</cite></div>
        
        <div class="BestConsole hide"><img src="images/ps2.jpg" alt="ps2" >
    <h2 >The Best Selling Console is the PlayStation 2</h2>
        <p >The PlayStation had 158mil sales, followed by the Nintendo DS with 154mil sales, then the Nintendo Switch 131mil sales.</p>
        <cite>https://www.statista.com/statistics/1101872/unit-sales-video-game-consoles/#:~:text=The%20PlayStation%202%20was%20first,over%20158%20million%20units%20worldwide.</cite></div>
        
        <div class="iconic hide"><img src="images/smash.jpg" alt="smash bros" >
    <h2>Most Iconic Characters</h2>
        <p>This one is more up to interpretation. On several lists they would be: Mario from the Mario games, Link from the Legend of Zelda, Pikachu from the Pokemon games, Pac-Man from Pac-Man, Master Chief from Halo, Sonic the Hedgehog from Sonic, etc. This list could go on for a long time.</p></div>
        
        </section>
    </main>

    <footer><p>&copy; Max Reitmayer 2024</p>
    </footer>
    </body>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="script.js"></script>
</html>

解决方案

1. 先修正HTML的小错误

原HTML里“Best Selling Console”按钮错用了BestSeries类,会导致点击时关联错误的div,需要改成BestConsole:

<button class="BestConsole">Best Selling Console</button>

2. 编写jQuery切换逻辑

在script.js中添加以下代码,核心用jQuery的.toggleClass()方法——它能自动切换类:存在则移除,不存在则添加,完美匹配你“点击显示、再点击隐藏”的需求:

$(document).ready(function() {
  // 给所有按钮绑定点击事件
  $('#buttons button').click(function() {
    // 获取当前按钮的类名,用来定位对应内容div
    var targetClass = $(this).attr('class');
    // 切换目标div的.hide类
    $('.' + targetClass).toggleClass('hide');
  });
});

3. 可选:实现“单内容显示”模式

如果希望点击新按钮时自动隐藏其他内容,只显示当前选中的,可以用以下代码:

$(document).ready(function() {
  $('#buttons button').click(function() {
    var targetClass = $(this).attr('class');
    // 先隐藏所有内容div
    $('#fact > div:not(#buttons)').addClass('hide');
    // 再显示当前点击对应的div
    $('.' + targetClass).removeClass('hide');
  });
});

关键知识点

  • $(document).ready():确保DOM加载完成后再执行JS,避免找不到元素。
  • .toggleClass('hide'):jQuery专门的类切换方法,比手动判断类是否存在再添加/移除更简洁高效。
  • $(this):指代当前被点击的按钮,通过它获取类名来精准定位目标div。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:25:00