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

JS alert无意义循环问题求助:猜歌游戏多次答对后异常

问题根源

你的问题出在每次答对后调用onPageLoad()会重复给提交按钮绑定点击事件。第一次加载页面绑了1个监听器,第一次答对后绑第2个,第二次答对绑第3个……每次点击按钮时,所有绑定过的监听器都会触发,而每个监听器拿着的是绑定当时的旧歌曲名称,所以就会出现先弹出错误提示(旧监听器的判断结果)、最后才弹出正确提示(最新监听器的判断结果)的情况,答对次数越多,绑定的监听器越多,问题越严重。

修复方案

推荐用「全局变量存储当前目标歌曲名+只绑定一次监听器」的方式,逻辑更简洁:

// 全局变量存储当前要猜的歌曲名和分数
let currentSongName = '';
let score = 0;

const onPageLoad = async () => {
  let songResults = await getSongData();
  let randomSong = songResults[Math.floor(Math.random() * songResults.length)];
  audioSound.src = randomSong.song_path;
  audioSound.load();
  albumCover.src = randomSong.photo_path;
  // 更新当前要猜的歌曲名
  currentSongName = randomSong.song_name;
};

// 只给提交按钮绑定一次点击事件,放在初始化阶段
submitButton.addEventListener("click", guessingGame);

const guessingGame = async () => {
  let input = document.getElementById("guessInputBox").value;
  if (input) {
    if (input.toLowerCase() === currentSongName.toLowerCase()) {
      alert('correct');
      score++;
      alert("that took " + score + " attempts");
      score = 0;
      onPageLoad();
      // 清空输入框,优化用户体验
      document.getElementById("guessInputBox").value = '';
    } else {
      alert('incorrect');
      alert(currentSongName);
      score++;
    }
  }
};

// 页面加载时执行初始化
onPageLoad();

如果坚持要保留原有的闭包传参逻辑,也可以通过「先移除旧监听器再添加新监听器」解决,但需要用命名函数:

let score = 0;
// 定义命名的监听器函数,方便后续移除
function submitHandler(randomSongName) {
  guessingGame(randomSongName);
}

const onPageLoad = async () => {
  let songResults = await getSongData();
  let randomSong = songResults[Math.floor(Math.random() * songResults.length)];
  audioSound.src = randomSong.song_path;
  audioSound.load();
  albumCover.src = randomSong.photo_path;
  // 先移除旧的监听器,再绑定新的
  submitButton.removeEventListener("click", submitHandler);
  submitButton.addEventListener("click", () => {
    submitHandler(randomSong.song_name);
  });
};

const guessingGame = async (songName) => {
  let input = document.getElementById("guessInputBox").value;
  if (input) {
    if (input.toLowerCase() === songName.toLowerCase()) {
        alert('correct');
        score++;
        alert("that took " + score + " attempts");
        score = 0;
        onPageLoad();
        document.getElementById("guessInputBox").value = '';
    } else {
        alert('incorrect');
        alert(songName);
        score++;
    }
  }
};

onPageLoad();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:20:48