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

JavaScript开发点击类游戏localStorage存值后页面刷新计数器重置问题求解

问题原因
  • 核心错误在LOAD函数的变量声明:你在函数内部用var重新声明了XP、KillCount变量,这两个是仅在LOAD函数内生效的局部变量,完全没有修改全局的对应变量。所以页面显示的数值看起来是对的,但点击图片加XP时调用的还是初始值为0的全局变量,自然就从1开始计数。
  • localStorage存储的值默认是字符串类型,取出后没有转成数字,后续计算可能出现字符串拼接的异常。
  • 页面刷新后没有自动读取存档的逻辑,必须手动点击加载按钮才会读档。
  • 代码存在语法问题:killCount函数没有正确闭合,checkXP函数存在递归死循环风险且无实际作用。
修复方案
  1. 去掉LOAD函数内的var声明,直接给全局变量赋值,同时将读取到的localStorage值转为整数,处理首次打开无存档的边界情况。
  2. 页面初始化时自动执行一次读档逻辑,刷新后自动恢复存档数据。
  3. 清理冗余错误的checkXP函数,修正killCount函数的闭合问题。
  4. 优化击杀数计算逻辑,避免单次增加XP超过25时漏统计击杀数。

修复后的完整代码如下:

<html>
    <head>
            <title> Menggokil Adventure </title>
    </head>
    <body> 
        <p>XP: <span id="XP">0</span></p>
        <p>KillCount <span id="KillCount">0</span></p>
        <img src="gokil.jpg" height="256px" width="256px"  onclick="addToXP(1)">
        <br> 
        <button onclick="SAVE()">Save Game Gokil ini</button> <button onclick="LOAD()">Load Game Gokil ini</button>
    </body>
</html>

<script>
  var XP = 0;
  var KillCount = 0;

  // 页面初始化自动读档
  window.onload = function() {
    LOAD();
  }

  function addToXP(amount) { 
    XP = XP + amount;
    document.getElementById("XP").innerHTML = XP;
    killCount(); 
  }

  function SAVE() {
    localStorage.setItem("XP", XP);
    localStorage.setItem("killcount", KillCount);
    console.log('存档成功,XP:', XP, '击杀数:', KillCount);
  } 

  function LOAD() {
    // 直接修改全局变量,转数字,无存档时默认0
    XP = parseInt(localStorage.getItem("XP")) || 0;
    KillCount = parseInt(localStorage.getItem("killcount")) || 0;
    document.getElementById("XP").innerHTML = XP;
    document.getElementById("KillCount").innerHTML = KillCount; 
  } 

  function killCount() {
    // 计算当前累计击杀数,避免漏加
    const currentKill = Math.floor(XP / 25);
    if (currentKill > KillCount) {
      KillCount = currentKill;
      document.getElementById("KillCount").innerHTML = KillCount;
    }
  }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:06:04