H1元素分数无法修改:乒乓球计分器按钮点击无响应修复请求
修复乒乓球计分器的分数更新问题
我正在开发一款乒乓球计分器,期望点击按钮时H1元素的分数值能更新,但分数始终停留在0。点击“sumPlayerOne”按钮时,H1元素的第一个分数应加1;点击“sumPlayerTwo”按钮时,第二个分数应加1。
问题根源
你的代码核心问题是只在页面初始化时设置了一次H1的内容,后续点击按钮更新scoreOne/scoreTwo变量后,没有重新同步更新H1的innerText,所以页面显示一直停留在初始的0 to 0。另外重置按钮也未实现功能,可一并补上。
修复后的JavaScript代码
const buttonOne = document.querySelector("#sumPlayerOne"); const buttonTwo = document.querySelector("#sumPlayerTwo"); const resetear = document.querySelector("#reset") const h1 = document.querySelector("#scoreKeeper") let scoreOne = 0; let scoreTwo = 0; // 封装更新分数显示的函数,避免重复代码 function updateScore() { h1.innerText = `${scoreOne} to ${scoreTwo}`; } buttonOne.addEventListener("click", (e) => { scoreOne += 1; // 简化写法,等价于scoreOne = scoreOne + 1 updateScore(); // 更新页面显示 }); buttonTwo.addEventListener("click", (e) => { scoreTwo += 1; updateScore(); // 更新页面显示 }); resetear.addEventListener("click", () => { scoreOne = 0; scoreTwo = 0; updateScore(); // 重置后更新显示 }); // 初始化显示分数 updateScore();
修改说明
- 新增
updateScore函数,专门负责将最新分数同步到H1元素,避免重复编写设置innerText的代码 - 点击按钮更新分数后,立即调用
updateScore刷新页面显示 - 补充重置按钮功能,点击后重置分数并更新显示
- 初始化时调用
updateScore,确保页面加载时就能看到正确的初始分数
原HTML代码(无需修改)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>scoreKeeper - JS</title> <link rel="stylesheet" href="scoreKeeper.css"> </head> <body> <div id="imageDiv"> <img src="https://media.istockphoto.com/id/503250996/photo/ping-pong-or-table-tennis-background-with-rackets.jpg?s=612x612&w=0&k=20&c=XSTF2456Iq81RxL_D887ikZOpyfEtUgEpPZGfTKrwRI=" alt="tableTennisImage"> </div> <div id="title"> <h3>Ping Pong Score Keeper</h3> </div> <div id="scoreDiv"> <h1 id="scoreKeeper"></h1> <p>Use the buttons below to keep the score</p> <h3>Playing To</h3> <select id="scoreLimiter"> <option value="7">7</option> <option value="11">11</option> <option value="21">21</option> </select> <button id="sumPlayerOne">1+ Player One</button> <button id="sumPlayerTwo">1+ Player Two</button> <button id="reset">Reset</button> </div> <script src="scoreKeeper.js"></script> </body> </html>
原CSS代码(次要,无需修改)
* { box-sizing: border-box; } body{ font-family: monospace; font-weight: 600; } #imageDiv { display: flex; justify-content: center; } img { width: 25rem; border-radius: 10px; } #title{ margin-top: 1rem; margin-bottom: 10px; padding-left: 1rem; border: 1px solid lightgray; margin-left: 5px; margin-right: 5px; border-radius: 10px ; } #scoreKeeper{ font-size: 300%; } #scoreDiv { border: 1px solid lightgray; padding-left: 1rem; padding-bottom: 1rem; border-radius: 10px ; margin-left: 5px; margin-right: 5px; } #scoreLimiter{ font-family: monospace; font-size: 17px; } #sumPlayerOne{ font-family: monospace; } #sumPlayerTwo{ font-family: monospace; } #reset{ font-family: monospace; }
内容的提问来源于stack exchange,提问作者matsolord
相关产品推荐
相关产品推荐

