HTML与JS:如何实现点击按钮后div内的textContent游戏结果持久显示
两个问题的核心根因
- 结果文本闪烁后消失:你把按钮嵌在
<form>标签内,且没有给按钮指定type属性,浏览器会默认将其识别为表单提交按钮,点击后会触发页面重载的默认行为,之前写入DOM的结果文本刚渲染就被刷新清空,自然无法留存。 - 替换
innerHTML后结果不显示:本质还是上面的表单刷新问题——你修改渲染属性的逻辑完全正确,但点击按钮后页面立刻重载,新写入的DOM内容刚生成就被冲掉,看起来就像innerHTML没有生效。等解决了表单提交触发的刷新问题,不管用textContent还是innerHTML都能正常渲染内容。
针对性代码调整
- 先解决表单默认提交的问题,两个方案二选一即可:
- 给所有按钮加上
type="button"属性,明确告知浏览器这不是表单提交按钮,无需触发表单重载 - 在按钮的点击事件回调里加
event.preventDefault(),拦截表单的默认提交行为
- 给所有按钮加上
- 修复代码里的隐藏报错点:原代码直接对
playerScore、computerScore做累加,但从未初始化这两个变量,会触发引用报错中断逻辑,需要提前声明并赋初始值0。 - 精简冗余逻辑:原代码全局定义的
computerSelection在传入函数后,又在函数内部被重新赋值,属于多余传参,可以直接在函数内部生成电脑的选择结果,减少无意义的变量传递。 - 优化对局判断逻辑:原代码仅写死了“石头”选项的判断分支,其余两个选择的逻辑缺失,可抽离通用胜负判断逻辑,适配三个选择按钮的交互。
调整后的可运行代码
HTML部分:
<html> <head> <title>石头剪刀布小游戏</title> <meta charset="UTF-8"/> </head> <body> <form> <button id="rockBtn" type="button">石头</button> <button id="paperBtn" type="button">布</button> <button id="scissorsBtn" type="button">剪刀</button> </form> <div id="results"></div> </body> <script src="main.js"></script> </html>
JavaScript部分:
// 提前初始化得分变量,避免未定义报错 let playerScore = 0; let computerScore = 0; function computerPlay(choices = ["rock", "paper", "scissors"]) { const randomIndex = Math.floor(Math.random() * choices.length); return choices[randomIndex]; } function playRound(playerSelection) { // 每局对局时随机生成电脑选择 const computerSelection = computerPlay(); const playerChoice = playerSelection.toLowerCase(); let resultText = ""; if (playerChoice === computerSelection) { resultText = `这局平局!你出了${playerChoice},电脑出了${computerSelection}`; } else if ( (playerChoice === "rock" && computerSelection === "scissors") || (playerChoice === "paper" && computerSelection === "rock") || (playerChoice === "scissors" && computerSelection === "paper") ) { playerScore++; resultText = `你赢了!${playerChoice}战胜${computerSelection}`; } else { computerScore++; resultText = `你输了!${computerSelection}战胜${playerChoice}`; } // 替换成innerHTML也能稳定展示,不会被页面刷新冲掉 document.getElementById("results").textContent = `${resultText} | 当前比分:你${playerScore} - 电脑${computerScore}`; } // 绑定各选择按钮的点击事件 document.getElementById("rockBtn").addEventListener("click", () => playRound("rock")); document.getElementById("paperBtn").addEventListener("click", () => playRound("paper")); document.getElementById("scissorsBtn").addEventListener("click", () => playRound("scissors"));
内容的提问来源于stack exchange,提问作者lblare123
相关产品推荐
相关产品推荐

