【问题标题】:Saving and loading in Javascript not working在Javascript中保存和加载不起作用
【发布时间】:2015-01-06 22:14:10
【问题描述】:

我目前正在用 HTML 和 Javascript 制作一个简单的游戏(我的第一个)。这是保存的代码:

function save()
{
  var save = {
    ducks: ducks,
    ponds: ponds,
    pondCost: pondCost,
    ponds: ponds,
    vacuums: vacuums,
    vacuumCost: vacuumCost,
    vacuum: vacuum,
    llama: llama,
    llamaCost: llamaCost,
   llamas: llamas
  }
  localStorage.setItem("save",JSON.stringify(save));
};

这是加载代码:

function load()
{
  var savegame = JSON.parse(localStorage.getItem("save"));
  if (typeof savegame.ducks !== "undefined") ducks = savegame.ducks;
  if (typeof savegame.ponds !== "undefined") ponds = savegame.ponds;
  if (typeof savegame.pond !== "undefined") pond = savegame.pond;
  if (typeof savegame.pondCost !== "undefined") pondCost = savegame.pondCost;
  if (typeof savegame.vacuums !== "undefined") vacuums = savegame.vacuums;
  if (typeof savegame.vacuum !== "undefined") vacuum = savegame.vacuum;
  if (typeof savegame.vacuumCost !== "undefined") vacuumCost = savegame.vacuumcost;
  if (typeof savegame.llama !== "undefined") llama = savegame.llama;
  if (typeof savegame.llamas !== "undefined") llamas = savegame.llamas;
  if (typeof savegame.llamaCost !== "undefined") llamaCost = savegame.llamaCost;
  document.getElementById('ponds').innerHTML = ponds;
  document.getElementById('vacuums').innerHTML = vacuums;
  document.getElementById('vacuumCost').innerHTML = nextCost;
  document.getElementById('pondCost').innerHTML = nextCost;
};

我还添加了一个重置​​功能,但是当我添加它并按下重置按钮时,保存不起作用! (或加载)

function reset()
{
  localStorage.removeItem("save")
}

所有这些按钮都附加到我的 HTML 中的一个按钮上。

在浏览器中玩游戏: https://dl.dropboxusercontent.com/u/104187515/TIGWNN/index.html

【问题讨论】:

  • 我想通了!我打开网络检查器,发现 2 个变量不存在,因此无法保存。我删除了它们,然后又弹出了一些错误!所以现在它固定了!
  • Puffychesses,我研究了你的作品,你的游戏对于初学者来说是一个很好的开始。我想帮助你完成你的项目。

标签: javascript function load save


【解决方案1】:

好吧,如果没有完全调试您的代码,当我点击保存时会出现错误。您在第 17 行的保存功能正在执行:

vacuum: vacuum,

您没有名为 Vacuum 的全局变量,但有一个名为 vacuums 的全局变量。该错误正在停止任何进一步的处理。

【讨论】:

    猜你喜欢
    • 2016-09-14
    • 2021-04-15
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多