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
相关产品推荐
相关产品推荐

