gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:44:06 26 4
gpt4 key购买 nike

我有一个页面,利用本地存储来保存单击按钮的次数:

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...";
}
}

我现在想要再添加 3 个按钮,并想要单独存储每个按钮的值。为了显示它,我知道我会引用适当的 ID,但我不确定如何存储这些值。我想我还有 3 个函数来执行此操作,并且需要为每个值创建一个变量?我走在正确的道路上吗?

最佳答案

简而言之,您可以执行以下操作将项目存储在 localStorage 中:

localStorage.firstButtonCount += 1;

localStorage.secondButtonCount +=1;

问题的关键在于 localStorage 的行为类似于 JavaScript 对象。因此,这意味着您应该记住,如果您使用 . 点表示法来执行此操作,则无法对来自变量并在运行时确定的键执行此操作。对于这种情况,请使用方括号表示法 []

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

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

关于javascript - 使用 HTML5 本地存储保存多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com