简体   繁体   English

如何在多个 html 页面上声明变量

[英]How to declare a variable over multiple html pages

I am making a quiz with a lifes system and the lifes system works but i wanna make it so for example, if you lose a life on q1 you will have 2/3 lives, but when you go onto question 2 you would still have 2/3 lives.我正在用生命系统进行测验,生命系统有效,但我想这样做,例如,如果你在第一季度失去生命,你将有 2/3 生命,但是当你 go 进入问题 2 时,你仍然会有 2 /3 生命。 I do not know how to do this.. Any help would be appreciated as i am a new javascripterer:D我不知道该怎么做.. 任何帮助将不胜感激,因为我是一个新的 javascripterer:D

js so far: (the lives code) js 到目前为止:(生活代码)

var lives = 3;
var loadLives = setInterval(showLives, 100);

function loseLife() {
    if (lives > 1) {
        lives = --lives;
    }
    else {
        location.href='fail.html';
    }
}

function showLives() {
    document.getElementById("lifeamount").innerHTML = lives;
}

Try to use local storage like this:尝试像这样使用本地存储:

// 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';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM