能否将document.getElementById纳入函数?罗马版猜拳代码疑问
问题解答
当然可以把document.getElementById放进函数里,这完全没问题,但你当前的实现思路存在错误,导致无法正确获取玩家的选择。
你的代码存在的核心问题
- 点击事件判断错误:你用
document.getElementById('0').onClick来判断按钮是否被点击,这是错误的用法。onclick(注意小写)是用来绑定事件处理函数的属性,不是用来检测点击行为的。 - 执行时机错误:页面加载时你就直接调用了
playerChooses()和compareChoices(),此时用户还没点击任何按钮,player1.currentChoice始终是null,直接比较会得到错误结果。
修正后的实现方案
给每个按钮绑定点击事件,当用户点击按钮时,再设置玩家选择并触发结果比较:
HTML代码(无需修改)
<h1>Rock, Paper, Scissors for Romans!</h1> <h2>Let's get into it: Lapis, Papyrus, Scalpellus</h2> <p>Look, it's the same, we just changed it to Latin words. There you go. You know how to play Rock, Paper, Scissors.<br> <br>Make your move: </p> <button id="0">Lapis</button> <button id="1">Papyrus</button> <button id="2">Scalpellus</button>
JavaScript代码
let cpu = { currentChoice: null, }; let player1 = { currentChoice: null, }; const choices = ["Lapis", "Papyrus", "Scalpellus"]; function computerChooses() { const cpuMove = Math.floor(Math.random() * 3); cpu.currentChoice = choices[cpuMove]; } function compareChoices() { computerChooses(); let result; if (cpu.currentChoice === player1.currentChoice) { result = `Tie! CPU and Player1 both chose ${cpu.currentChoice}`; } else if (cpu.currentChoice === choices[0]) { result = player1.currentChoice === choices[1] ? `Player1 wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}` : `CPU wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}`; } else if (cpu.currentChoice === choices[1]) { result = player1.currentChoice === choices[2] ? `Player1 wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}` : `CPU wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}`; } else if (cpu.currentChoice === choices[2]) { result = player1.currentChoice === choices[0] ? `Player1 wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}` : `CPU wins! CPU chose ${cpu.currentChoice} and Player1 chose ${player1.currentChoice}`; } displayWinner(result); } function displayWinner(result) { // 每次显示结果前清空旧结果,避免重复堆积 const existingResult = document.querySelector('.result'); if (existingResult) { existingResult.remove(); } const whoWon = document.createElement('p'); whoWon.className = 'result'; whoWon.innerText = result; document.body.appendChild(whoWon); } // 给每个按钮绑定点击事件 choices.forEach((_, index) => { const button = document.getElementById(index); button.addEventListener('click', () => { player1.currentChoice = choices[index]; compareChoices(); }); });
关键改进点
- 使用
addEventListener给按钮绑定点击事件,确保用户点击时才触发选择逻辑 - 移除了提前调用的
playerChooses(),改为点击时动态设置玩家选择 - 用模板字符串优化了结果字符串拼接,代码更简洁
- 添加了清空旧结果的逻辑,避免页面上堆积多个结果
内容的提问来源于stack exchange,提问作者jlandie
相关产品推荐
相关产品推荐

