HTML5 本地 save/load

HTML5 Local save/load

我正在尝试按照此站点“Link to Tutorial”中的教程来制作放置游戏。

它显示了制作简单的本地保存功能的简单方法,但由于某些原因我无法让它工作。他告诉我们做一个函数这个那个,但没有说明它应该是什么样子。

我搜索了 google 并看到了许多不同的方法,我得到了一些工作但不完全而且它们​​不够简单,因为我缺乏 HTML 的知识。 欢迎并感谢任何帮助 :) 提前致谢。

function save(){
    var save = {
    cookies: cookies,
    cursors: cursors
}
localStorage.setItem("save",JSON.stringify(save));
};

function load(){
    var savegame = JSON.parse(localStorage.getItem("save"));
    if (typeof savegame.cookies !== "undefined") cookies = savegame.cookies;
};

var cookies = 0;

function cookieClick(number) {
  cookies = cookies + number;
  document.getElementById("cookies").innerHTML = cookies;
};

var cursors = 0;

function buyCursor() {
  var cursorCost = Math.floor(10 * Math.pow(1.1, cursors)); //works out the cost of this cursor
  if (cookies >= cursorCost) { //checks that the player can afford the cursor
    cursors = cursors + 1; //increases number of cursors
    cookies = cookies - cursorCost; //removes the cookies spent
    document.getElementById('cursors').innerHTML = cursors; //updates the number of cursors for the user
    document.getElementById('cookies').innerHTML = cookies; //updates the number of cookies for the user
  };
  var nextCost = Math.floor(10 * Math.pow(1.1, cursors)); //works out the cost of the next cursor
  document.getElementById('cursorCost').innerHTML = nextCost; //updates the cursor cost for the user
};


function save() {
  var save = {
    cookies: cookies,
    cursors: cursors
  }
  localStorage.setItem("save", JSON.stringify(save));
};

function load() {
  var savegame = JSON.parse(localStorage.getItem("save"));
  if (typeof savegame.cookies !== "undefined") cookies = savegame.cookies;
}


window.setInterval(function() {

  cookieClick(cursors);

}, 1000);
<html>

<head>
  <link rel="stylesheet" type="text/css" href="interface.css" />
</head>

<body>
  <button onclick="cookieClick(1)">Click Me!</button>
  <br />Cookies: <span id="cookies">0</span>
  <br />
  <button onclick="buyCursor()">Buy Cursor</button>
  <br />Cursors: <span id="cursors">0</span>
  <br />Cursor Cost: <span id="cursorCost">10</span>
  <script type="text/javascript" src="main.js"></script>
</body>

</html>

您的浏览器可能不支持本地存储。 您可以使用 Modernizr 检查浏览器的本地存储支持。 在这里阅读:http://diveintohtml5.info/detect.html

还要确保您在代码中调用了 save() 方法(我在您的代码中没有看到它)