HTML按钮控制计数器数值无变化问题排查求助
你的代码有两处核心错误导致功能失效:
- 全局计数器变量
counterNum未初始化,初始值为undefined,参与数值运算后结果为NaN,无法正常更新数值 - 你用
.value属性修改标签的内容,只有表单类元素(input、textarea等)支持value属性,普通文本标签要修改内容需使用
innerText或textContent属性
修复后的完整代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Counter</title> </head> <body> <br><br><br><br> <font size="4"> <h1 align="center">Counter</h1> </font> <font size="5"> <h2 align="center" id="counter">0</h2> </font> <div align="center"> <br> <button onclick="decrease()" >Decrease</button> <button onclick="reset()" >Reset</button> <button onclick="increase()" >Increase</button> </div> <script> // 初始化计数器变量为0 var counterNum = 0 function decrease() { counterNum = counterNum - 1 // 使用innerText更新h2内容 document.getElementById("counter").innerText = counterNum; } function reset() { // 直接赋值0更稳妥,避免运算异常 counterNum = 0 document.getElementById("counter").innerText = counterNum; } function increase() { counterNum = counterNum + 1 document.getElementById("counter").innerText = counterNum; } </script> </body> </html>
内容的提问来源于stack exchange,提问作者Atramentis
相关产品推荐
相关产品推荐

