簡體   English   中英

localStorage 在 glitch.com 上無法正常工作?

[英]localStorage not working properly on glitch.com?

我創建了一個增量游戲,並有興趣將變量存儲在 localStorage 中。 我決定先在小范圍內嘗試它是明智的。 我閱讀了相當多的 w3 教程和堆棧溢出問題,但我無法讓它發揮作用。 我寫了以下內容:

var val; //declares test variable
function incr() {
  val += 1;
  document.getElementById("count").innerHTML = val; //update the div where the variable is displayed
  console.log(val)
} //called on by an html button
function save() {
  var saveGame = {
    val: val
  }
  localStorage.setItem("saveGame",JSON.stringify(saveGame));
}
setInterval(function() {
  save();
  console.log("Game Saved.")
}, 100)
function saveDataTest() {
  if (localStorage.getItem("saveGame") || null) {
    load();
  } //called on by 'onload' event

}
function load() {
  var loadGame = JSON.parse(localStorage.getItem("saveGame"));
  val = loadGame.val;
} //split string into an object/variable and use said object/variable to define variable
 if (val == undefined){val = 0;}

正如我在標題中提到的,我正在使用 Glitch.com 並且考慮到我找不到任何問題,我認為這可能是網站的錯。 如果我在代碼中犯了錯誤,請糾正我。

var val = 0; //declares test variable
function incr() {
  val += 1;
  document.getElementById("count").innerHTML = val; //update the div where the variable is displayed
  console.log(val)
} //called on by an html button
function save() {
  var saveGame = {
    val: val.toString(),
  }
  localStorage.setItem("saveGame",JSON.stringify(saveGame));
}
window.onload = function() {
  loadGame = JSON.parse(localStorage.getItem("saveGame"));
  load();
};
setTimeout(function() {setInterval(function() {
  save();
  console.log("Game Saved.")
}, 10)},400) //use delay so that game does not save immediately after loading

}
function load() {
if (!(localStorage.getItem("saveGame") == null)) {
  val = Number(loadGame.val);}
} //split string into an object/variable and use said object/variable to define variable

使用 Number() 和 .toString() 將字符串轉換為數字,反之亦然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM