简体   繁体   English

使用HTML5本地存储保存多个值

[英]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. 现在,我想再添加3个按钮,并分别存储每个按钮的值。 To display it I know I would refer to the appropriate ID but I'm not sure how to store these values. 要显示它,我知道我会引用适当的ID,但是我不确定如何存储这些值。 I imagine that I will have 3 further functions that will perform this and need to create a variable for each of the values? 我想我将有3个进一步的函数来执行此操作,并且需要为每个值创建一个变量? Am i on the correct path? 我在正确的道路上吗?

In short, you can do the following to store items in localStorage : 简而言之,您可以执行以下操作将项目存储在localStorage

localStorage.firstButtonCount += 1;

localStorage.secondButtonCount +=1;

The crux of the matter is that localStorage behaves like a javascript object. 问题的关键在于localStorage行为类似于javascript对象。 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对象。 localStorage.keyName = value is totally acceptable. localStorage.keyName = value是完全可以接受的。 To see what it looks like open your browser dev tools and enter localStorage in the console. 要查看其外观,请打开浏览器开发工具,然后在控制台中输入localStorage You will see that it is basically just an object. 您将看到它基本上只是一个对象。

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

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