点击网页按钮时如何将按钮值作为函数参数进行传递
问题根因
代码中从未定义playerSelection变量,三个点击回调直接传入未声明赋值的变量,运行时自然会得到undefined。另外你在全局初始化时就执行了一次computerPlay()赋值给computerSelection,后续所有点击都会复用第一次生成的电脑出拳结果,游戏逻辑存在缺陷。
修复方案
两种常用实现方式可按需选择:
方式1:单按钮独立传值(逻辑直白易理解)
每个按钮对应固定出拳结果,点击回调内直接声明对应出拳值,同时每轮点击重新生成电脑出拳:
const rock = document.querySelector('.rock'); const paper = document.querySelector('.paper'); const scissors = document.querySelector('.scissors'); // 保留你已实现的computerPlay、playRound函数即可 rock.addEventListener('click', function(){ const playerSelection = 'ROCK'; const computerSelection = computerPlay(); playRound(playerSelection, computerSelection); }); paper.addEventListener('click', function(){ const playerSelection = 'PAPER'; const computerSelection = computerPlay(); playRound(playerSelection, computerSelection); }); scissors.addEventListener('click', function(){ const playerSelection = 'SCISSORS'; const computerSelection = computerPlay(); playRound(playerSelection, computerSelection); });
方式2:事件委托统一处理(代码精简无重复)
给三个按钮绑定同一个回调,通过事件对象拿到被点击的按钮节点,直接读取节点内容作为玩家出拳,后续新增选项也不用重复写绑定逻辑:
// 一次性选中所有出拳按钮 const choiceButtons = document.querySelectorAll('.rock, .paper, .scissors'); // 保留你已实现的computerPlay、playRound函数即可 choiceButtons.forEach(button => { button.addEventListener('click', function(e){ // 读取按钮文本,做去空格、转大写处理适配原有判断逻辑 const playerSelection = e.target.textContent.trim().toUpperCase(); const computerSelection = computerPlay(); playRound(playerSelection, computerSelection); }) })
优化建议
如果不想依赖按钮文本做判断,可以给按钮加value属性存出拳值,容错率更高:
<button class="rock" value="ROCK">石头</button> <button class="paper" value="PAPER">布</button> <button class="scissors" value="SCISSORS">剪刀</button>
回调里直接用const playerSelection = e.target.value就能拿到出拳值,后续改按钮显示文案也不会影响逻辑判断。
内容的提问来源于stack exchange,提问作者Osama Mohammad
相关产品推荐
相关产品推荐

