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

如何在forEach循环的onclick事件中返回值并用于比较逻辑?

解决点击按钮无法返回值并传入compare函数的问题

问题根源

  1. 点击事件的回调函数返回值无法被外层的playerSelect捕获——浏览器不会把事件回调的返回值传递给外层函数,所以playerSelect实际没有返回任何内容。
  2. compare函数的参数写法错误,你写成了(playerChoise()),这会直接尝试执行不存在的playerChoise函数,正确写法是定义参数名,比如(playerChoise)。
  3. 变量RPS未用const/let声明,会成为全局变量,容易引发命名冲突。

修改方案

不需要让playerSelect返回值,直接在按钮点击时调用compare并传入按钮值即可,这是最直接的实现方式。

修正后的playerSelect函数

const playerSelect = () => {
  // 用const声明变量,避免全局污染
  const RPS = document.querySelectorAll(".rpsButton");
  RPS.forEach(button => {
    button.onclick = () => {
      // 点击时直接调用compare,传入当前按钮的值
      compare(button.value);
    };
  });
};

修正后的compare函数

注意统一字符串大小写(按钮value是首字母大写,判断里写的是小写,会导致匹配失败,用toLowerCase()统一转换更稳妥):

// 假设score是外层作用域声明的变量
let score = 0;
const compare = (playerChoise) => {
  const computerChoice = getComputerChoice();
  // 统一转成小写进行比较
  if (computerChoice.toLowerCase() === "rock" && playerChoise.toLowerCase() === "paper") {
    score++;
    console.log(`得分+1,当前分数:${score}`);
  }
};

// 补充getComputerChoice函数(如果未实现的话)
const getComputerChoice = () => {
  const choices = ["Rock", "Paper", "Scissors"];
  const randomIndex = Math.floor(Math.random() * choices.length);
  return choices[randomIndex];
};

最后绑定事件

确保页面加载完成后再绑定按钮点击事件:

document.addEventListener("DOMContentLoaded", playerSelect);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:40:42