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

异步函数绑定事件监听时回调参数undefined问题求助

问题解决:点击事件绑定中参数传递导致undefined的问题

核心原因

你在绑定点击事件时犯了一个常见错误:submitButton.addEventListener("click", guessingGame(randomSong.song_path)) 这行代码会立即执行guessingGame函数,而不是把它作为点击事件的回调函数。此时函数执行没有正确的触发上下文,且后续点击按钮时,实际调用的是这个函数的返回值(你的guessingGame没有返回值,即undefined),所以函数内部的songPath自然是undefined。

两种修复方案

方案1:用箭头函数包裹回调

通过箭头函数延迟guessingGame的执行,确保点击按钮时才传递参数:

submitButton.addEventListener("click", () => guessingGame(randomSong.song_path))

方案2:用bind绑定参数

利用Function.prototype.bind创建绑定了参数的新函数作为回调:

submitButton.addEventListener("click", guessingGame.bind(null, randomSong.song_path))

修改后的完整代码示例

//页面加载时执行的异步函数,获取歌曲数据并显示初始歌曲和封面
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.addEventListener("click", () => guessingGame(randomSong.song_path))
};

//点击按钮时执行的异步函数,检查输入答案是否匹配
const guessingGame = async (songPath) => {
  let input = document.getElementById("guessInputBox").value;
  if (input) {
    if (input === songPath) {
        alert('正确')
        score++;
        alert(`总共尝试了 ${score} 次`);
        score = 0;
        changeSong();
    } else {
        alert('错误')
        alert(songPath);
        score++;
    };
  };
};

额外注意点

  • 确保score变量在全局或两个函数都能访问的作用域中定义,否则会引发未定义错误。
  • 如果changeSong函数会更换歌曲,记得重新绑定点击事件(或先解绑旧事件再绑定新的),避免点击时使用旧的歌曲路径参数。

内容的提问来源于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 13:15:33