简体   繁体   中英

Saving multiple values using HTML5 local Storage

I have a page that utilises local storage to hold the amount of times a button is clicked:

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
            localStorage.clickcount = Number(localStorage.clickcount)+1;
        } else {
            localStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "" + localStorage.clickcount + ".";
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}

I now want to add 3 more buttons and want to store the values for each of these separately. To display it I know I would refer to the appropriate ID but I'm not sure how to store these values. I imagine that I will have 3 further functions that will perform this and need to create a variable for each of the values? Am i on the correct path?

In short, you can do the following to store items in localStorage :

localStorage.firstButtonCount += 1;

localStorage.secondButtonCount +=1;

The crux of the matter is that localStorage behaves like a javascript object. So, it means you should keep in mind that if you use . dot notation to do this, you cannot do it for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case.

var my = 'firstButtonCount';
var second = 'secondButtonCount';

if(something > 10){
localStorage[my] += 1; // Determined dynamically
} else{
localStorage[second] += 1; 
}

You can continue to use dot notation to add new items to your localStorage object. localStorage.keyName = value is totally acceptable. To see what it looks like open your browser dev tools and enter localStorage in the console. You will see that it is basically just an object.

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