You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用<h1>显示JavaScript变量?变量设为0却显示undefined

问题分析与修复

你的代码里有几个关键问题导致Game.points显示undefined:

  • 你在Game函数里声明的points是局部变量,不属于Game函数的属性,所以外部(包括函数内部)访问Game.points时,这个属性根本不存在,自然返回undefined。
  • HTML结构错误:<center>标签放在了<body>外面,不符合规范,页面加载逻辑也会受影响。
  • 初始值用字符串"0"的话,后续点击做+1操作会变成字符串拼接(比如"0"+1得到"01"),应该用数字类型的0。
  • 页面加载时调用Game(),但此时你还没给Game.points赋值,直接把Game.points赋值到DOM里当然是undefined。

修正后的完整代码

<!DOCTYPE html>
<html>
<body onload="initGame()">
    <center>
        <img onclick="Game.points += 1; updatePoints()" 
             src="https://static.wikia.nocookie.net/villains/images/5/5d/Frieza.png/revision/latest?cb=20200625063534" 
             width="350px">
    </center>
    <h1>The value for number is: <span id="myText"></span></h1>

    <script>
        // 定义Game对象,存储points属性
        const Game = {
            points: 0
        };

        // 初始化游戏,更新初始分数显示
        function initGame() {
            updatePoints();
        }

        // 专门用来更新页面上的分数显示
        function updatePoints() {
            document.getElementById("myText").innerHTML = Game.points;
        }
    </script>
</body>
</html>

关键修改说明

  • 把Game改成一个对象,直接挂载points属性,这样全局都能正确访问Game.points。
  • 拆分初始化和更新DOM的逻辑:initGame()负责初始化,updatePoints()专门同步页面分数,点击图片时先加分再调用更新函数,确保页面和变量值一致。
  • 修复HTML结构,把所有内容放到<body>标签内,符合HTML规范。
  • 初始points设为数字0,这样+=1会做正确的数值加法。

内容的提问来源于stack exchange,提问作者nm_9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:43:17