如何为石头剪刀布游戏的三个按钮统一添加事件监听器?
批量为石头剪刀布游戏按钮添加事件监听器
我正在开发一款简易石头剪刀布(Quick Rock, Paper, Scissors)游戏,目前需要实现识别玩家点击按钮的功能。当前我只能逐个处理按钮的值,想咨询是否可以为三个按钮统一添加函数与事件监听器,或者通过获取按钮的NodeList并使用forEach方法来批量添加功能?
当然可以批量添加事件监听器,这能有效减少代码冗余,提升可维护性。具体实现方案如下:
核心优化点
- 批量选择按钮:通过共同类名
button1一次性获取所有游戏选择按钮,用forEach()遍历绑定事件 - 通用事件处理:编写统一的点击回调函数,从按钮属性中提取玩家选择
- 简化胜负判断:用对象存储胜负规则,替代冗长的if-else分支
- 完善游戏逻辑:添加计分、获胜判断与重置功能
修改后的完整JavaScript代码
const gameButtons = document.querySelectorAll('.button1'); const resetButton = document.querySelector('.reset'); const whoWonTheRound = document.querySelector('#log'); const computerLog = document.querySelector('#computer'); const humanLog = document.querySelector('#human'); // 初始化分数 let humanScore = 0; let computerScore = 0; // 电脑随机选择 const getComputerChoice = () => { const choices = ['rock', 'paper', 'scissor']; const randomNum = Math.floor(Math.random() * 3); return choices[randomNum]; }; // 判断单轮胜负,返回结果文本并更新分数 const playRound = (playerSelection, computerSelection) => { if (playerSelection === computerSelection) { return `It's a DRAW!`; } // 用对象存储胜负规则,简洁易扩展 const winConditions = { rock: 'scissor', paper: 'rock', scissor: 'paper' }; if (winConditions[playerSelection] === computerSelection) { humanScore++; return `You win! ${playerSelection.charAt(0).toUpperCase() + playerSelection.slice(1)} beats ${computerSelection}`; } else { computerScore++; return `You lose! ${computerSelection.charAt(0).toUpperCase() + computerSelection.slice(1)} beats ${playerSelection}`; } }; // 更新分数显示并检查游戏结束条件 const updateScore = () => { humanLog.textContent = `Your Score: ${humanScore}`; computerLog.textContent = `Computer Score: ${computerScore}`; // 一方达到5分则结束游戏 if (humanScore === 5) { whoWonTheRound.textContent = `🎉 You won the game!`; gameButtons.forEach(btn => btn.disabled = true); } else if (computerScore === 5) { whoWonTheRound.textContent = `💻 Computer won the game!`; gameButtons.forEach(btn => btn.disabled = true); } }; // 按钮点击统一处理函数 const handleButtonClick = (e) => { // 从按钮的第一个类名获取玩家选择(rock/paper/scissor) const playerSelection = e.target.classList[0]; const computerSelection = getComputerChoice(); const roundResult = playRound(playerSelection, computerSelection); whoWonTheRound.textContent = roundResult; updateScore(); }; // 批量为按钮添加点击事件监听器 gameButtons.forEach(button => { button.addEventListener('click', handleButtonClick); }); // 重置游戏功能 resetButton.addEventListener('click', () => { humanScore = 0; computerScore = 0; whoWonTheRound.textContent = ''; updateScore(); // 重新启用按钮 gameButtons.forEach(btn => btn.disabled = false); });
代码说明
- 批量绑定事件:
document.querySelectorAll('.button1')获取所有游戏按钮,通过forEach循环给每个按钮绑定click事件,避免重复代码 - 简化胜负判断:用
winConditions对象存储每种选择能击败的选项,替代原有的9条if-else判断,代码更简洁且易于扩展 - 完整游戏流程:添加了分数统计、获胜判断(先到5分获胜),以及重置功能,让游戏逻辑更完整
- DOM操作优化:统一管理分数显示与结果文本,避免重复的DOM查询
内容的提问来源于stack exchange,提问作者Angel94124
相关产品推荐
相关产品推荐

