如何在HTML页面显示本地存储的值
How to display the value the local storage holds on the HTML page
我有两个问题:
当我加载 HTML 页面时,我查看“调试”中的检查,它不断说本地存储未定义
如何在HTML页面显示本地存储值
JS代码:
var loadLives = setInterval(showLives, 100);
// get lives from localstorage
var livesInStorage = window.localstorage.getItem('lives');
let lives;
if(livesInstorage) {
//parse localstorage data to Int
lives = parseInt(livesInstorage, 10);
}
else {
// initial value (in this case: 3)
lives = 3;
}
function loseLife() {
if (lives > 1) {
lives = --lives;
// set changed value in localStorage
window.localstorage.setItem('lives', lives);
}
else {
location.href='fail.html';
}
}
function showLives() {
document.getElementById("lifeamount").innerHTML = window.localstorage.getItem('lives');
}
从您分享的代码中我可以看到您将变量 'lives' 设置为 3 作为初始值,但您没有在本地存储中设置它。
您只在调用 'loseLives' 时将其设置在本地存储中,但我没有看到对此函数的调用。
另外,你打错了。你写的是 localstorage 而不是 localStorage.
我有两个问题:
当我加载 HTML 页面时,我查看“调试”中的检查,它不断说本地存储未定义
如何在HTML页面显示本地存储值
JS代码:
var loadLives = setInterval(showLives, 100);
// get lives from localstorage
var livesInStorage = window.localstorage.getItem('lives');
let lives;
if(livesInstorage) {
//parse localstorage data to Int
lives = parseInt(livesInstorage, 10);
}
else {
// initial value (in this case: 3)
lives = 3;
}
function loseLife() {
if (lives > 1) {
lives = --lives;
// set changed value in localStorage
window.localstorage.setItem('lives', lives);
}
else {
location.href='fail.html';
}
}
function showLives() {
document.getElementById("lifeamount").innerHTML = window.localstorage.getItem('lives');
}
从您分享的代码中我可以看到您将变量 'lives' 设置为 3 作为初始值,但您没有在本地存储中设置它。 您只在调用 'loseLives' 时将其设置在本地存储中,但我没有看到对此函数的调用。
另外,你打错了。你写的是 localstorage 而不是 localStorage.