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

addEventListener使用问题及if语句无法执行的技术求助

问题分析与修复方案

你的代码核心问题有两个:

  1. addEventListener 方法的返回值是 undefined,不是布尔值,所以你后面写的 if(scalpellusButton === true) 这类判断完全不会触发,自然没法给 playerChoice 赋值。
  2. 点击按钮时,只调用了生成电脑选择的函数,但没有把返回值存到 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:50:22