javascript - localStorage 在 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() 将字符串转换为数字,反之亦然。
推荐阅读
- xslt - 对从参考列表中收集的属性进行排序
- can-bus - 如何修复 CAN 连接错误?
- ios - 在搜索栏上键入会破坏布局
- ios - 关于在 swift 中使用 socket.io 在聊天应用程序中发送图像的问题
- javascript - 更新模态引导程序和 ajax
- javascript - JQuery : troubles selecting an html element that is clicked on
- c# - 永久用户设置
- python - InvalidArgumentError:与 Keras LSTM 网络不兼容的形状
- cassandra - Cassandra:使用一个字母作为分片键来减少集群的负载
- soap - 将后端集成到前端