简体   繁体   中英

Keep a var when updating the code

I wanna make a thing in javascript and html and I've got a problem.

I've a selection page where I can click on 8 different buttons, and I want a var to take the id of this button. This button throw me on an other page, which have to use this var.

The problem is that when the code is called once again in the second page (to return the var in my main function otherwise it's not working), this code is updated and my var is obviously reset to 0;

I want to keep the value of this var when I call it again in my other page.

Thank you !

levelSelected = 0;

// Récupère le click 
for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html';
    });
}

One way of doing it beside localStorage or cookies is to pass it in the URL, ie using parameters:

levelSelected = 0;

// Récupère le click 
for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html?levelSelected=' + levelSelected;
    });
}

Have a look at How to retrieve GET parameters from javascript? to see how you can later retrieve the parameters in the next page.

Also How can I get query string values in JavaScript? as Terry suggested in the comments in your answer.

Edit :

Just in case you're not familiar with GET properties - you have have any number of them, just the first one must be preceded by a ? while all the other ones must be preceded by a & .

So:

location.href='level.html?levelSelected=' + levelSelected + '&otherParam' + paramValue;

Try local storage.

for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html';
        localStorage.id = levelSelected;
    });
}

Then on the page you want to use it on call the var back.

localStorage.getItem('levelSelected');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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