addEventListener使用问题及if语句无法执行的技术求助
问题分析与修复方案
你的代码核心问题有两个:
addEventListener方法的返回值是 undefined,不是布尔值,所以你后面写的if(scalpellusButton === true)这类判断完全不会触发,自然没法给playerChoice赋值。- 点击按钮时,只调用了生成电脑选择的函数,但没有把返回值存到
computerChoice变量里,也没在点击事件里处理玩家选择的赋值逻辑。
修复后的代码
// 游戏基础变量 const gameChoices = ["Scalpellus","Papyrus","Lapis"]; let playerChoice = null; let computerChoice = null; // 生成电脑随机选择 function computerChooses(){ const randomIndex = Math.floor(Math.random() * gameChoices.length); return gameChoices[randomIndex]; } // 处理玩家点击的通用函数 function handlePlayerChoice(choice) { // 给玩家选择赋值 playerChoice = choice; // 生成并存储电脑选择 computerChoice = computerChooses(); // 这里可以添加对战结果判断的逻辑,比如调用判断胜负的函数 console.log(`玩家选择:${playerChoice},电脑选择:${computerChoice}`); } // 给每个按钮绑定点击事件 document.getElementById("scalpellus").addEventListener("click", () => handlePlayerChoice(gameChoices[0])); document.getElementById("papyrus").addEventListener("click", () => handlePlayerChoice(gameChoices[1])); document.getElementById("lapis").addEventListener("click", () => handlePlayerChoice(gameChoices[2]));
关键修改点说明
- 新增了
handlePlayerChoice通用函数,接收玩家的选择作为参数,统一处理「赋值玩家选择」「生成电脑选择」的逻辑,避免重复代码。 - 给每个按钮绑定点击事件时,用箭头函数调用
handlePlayerChoice,并传入对应的选项值,这样点击按钮时直接完成玩家选择的赋值。 - 修复了
computerChooses函数里未声明的变量问题(原代码里的CompRandoChoice没有用let/const声明,会变成全局变量,这是不良写法)。 - 去掉了无效的
if判断逻辑,因为那部分完全起不到作用。
你可以在 handlePlayerChoice 函数里继续添加胜负判断的代码,比如对比 playerChoice 和 computerChoice,然后输出结果。
内容的提问来源于stack exchange,提问作者turtlewalker
相关产品推荐
相关产品推荐

