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

如何用JavaScript切换歌曲时更新id为title的h2标签内容?

解决歌曲切换时标题不更新的问题

看起来你已经搭好了点唱机的基础功能,但确实漏掉了更新歌曲标题的关键步骤!我帮你梳理下问题和修复方案:

问题根源

你的代码里完全没有更新id="title"的h2标签内容的逻辑,Jukebox()函数只负责加载音频并播放,压根没处理标题显示的部分。另外,name这个变量名不太合适——它是JavaScript的全局对象属性,容易引发意外冲突,建议改成songNames这类更清晰的名字。

修复步骤

  1. 优化变量命名(可选但推荐):把name数组改成songNames,避免命名冲突
  2. 添加标题更新逻辑:在Jukebox()函数里,获取标题元素并设置它的内容为当前歌曲名称
  3. 初始化显示标题:确保页面加载时就显示第一首歌的名字,而不是空标签

修改后的完整代码

JavaScript 部分

var songList = ["audio/classic.mp3", "audio/rococo.mp3", "audio/test.mp3"];
// 重命名数组避免全局变量冲突
var songNames = ["One", "Two", "Three"];

var music = new Audio(); // 这里不用传songList,后续会动态设置src
var currentSong = 0;

window.onload = Jukebox;

function Jukebox() {
    music.src = songList[currentSong];
    // 核心:更新标题标签内容
    document.getElementById('title').textContent = songNames[currentSong];
    music.play();
}

function togglePlay() {
    return music.paused ? music.play() : music.pause();
};

function stop() {
    music.pause();
    music.currentTime = 0; // 额外优化:停止时重置播放进度到开头
}

function nextSong() {
    currentSong++;
    // 不要写死判断值,用数组长度更灵活,后续加歌不用改这里
    if (currentSong >= songList.length) {
        currentSong = 0;
    }
    Jukebox();
}

HTML 部分(无需修改,保持原样即可)

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="Jukebox.css">
    <link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
</head>

<body>
    <header>
    </header>
    <main>
        <header>
        </header>
        <main>
            <div class="container">
                <h2 id="title"></h2>
                <div class="page0ne">
                    <button onclick="togglePlay()" class="pause"><h1>Play</h1></button>
                    <button onclick="stop()" class="stop"><h1>Stop</h1></button>
                    <button onclick="nextSong()" id="next"><h1>Next</h1></button>
                </div>
            </div>
        </main>
        <footer>
        </footer>
    </main>
    <footer>
        <script src="Jukebox.js"></script>
    </footer>
</body>

</html>

额外优化说明

  • 把currentSong > 2改成currentSong >= songList.length:以后添加新歌曲到数组时,不用手动修改判断条件,代码扩展性更强
  • 给stop()函数加上music.currentTime = 0:停止播放时自动重置进度到开头,符合用户使用习惯

这样修改后,点击「Next」按钮切换歌曲时,h2标签就会同步显示当前歌曲名称,页面加载时也会自动显示第一首歌的名字啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:15:56