HTML5本地保存/加载

时间:2015-01-08 05:56:11

标签: html5 save local

我试图关注这个网站的教程" Link to Tutorial"做一个空闲的游戏。

它显示了简单的本地保存功能,但由于某些原因我无法使其正常工作。他讲述了这个和那个功能,但没有说明它应该是什么样子。

我搜索谷歌并看到了许多不同的方式,我得到了一些工作,但没有完全,他们不够简单,因为我缺乏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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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

另外请确保您在代码中调用save()方法(我不会在您的代码中看到它)