首页 > 解决方案 > 加载仅在单击按钮后有效

问题描述

我为我的增量游戏制作了“保存和加载”功能。

它们都可以工作,但是当我加载数据时,我必须单击一个按钮来“更新”这些值。这不是主要货币(scrap)的问题,而是变量collector、collectorCost、drone和droneCost的问题。

两个部分都有相同的代码,所以我不明白为什么它不应该自动更新。

单击按钮时调用“保存和加载”功能

我不知道我是否需要显示更多代码。我对这整个场景有点陌生:)。

编辑:在页面加载时尝试了load(),但这并没有改变任何东西。

<button onclick="save()">Save Game</button>
<button onclick="load()">Load Game</button>
function save(){
  var save = {
    scrap: scrap,
    collector: collector,
    collectorCost: collectorCost,
    drone: drone,
    droneCost: droneCost
  };
  localStorage.setItem("save",JSON.stringify(save));
};

function load(){
  var savegame = JSON.parse(localStorage.getItem("save"));
  if(typeof savegame.scrap !== "undefined") scrap = savegame.scrap;
  if(typeof savegame.collector !== "undefined") collector = savegame.collector;
  if(typeof savegame.collectorCost !== "undefined") collectorCost = savegame.collectorCost;
  if(typeof savegame.drone !== "undifined") drone = savegame.drone;
  if(typeof savegame.droneCost !== "undifined") droneCost = savegame.droneCost;
};

我希望这些数字会自动更新,这适用于主要货币,但不适用于:collectorcollectorCostdronedroneCost

他们只有在我点击按钮购买任何一个之后才会改变

标签: javascripthtml

解决方案


推荐阅读