gpt4 book ai didi

javascript - 在 JAVASCRIPT 中重新加载页面时保存变量的当前值

转载 作者:行者123 更新时间:2023-12-01 04:03:40 26 4
gpt4 key购买 nike

有没有办法在页面刷新时保留变量值(如果有的话)

var x=0;

但是用户做了一些事情,使该值变成

x=4;

然后刷新页面,有没有办法将 x 变量的值保留为 4,否则它将始终重置为原始值?

我编写了 2 个函数来设置和获取如下值:

     function SetlifeCounter()
{
life = 3;
localStorage.setItem("life", life);
}

function GetlifeCounter()
{
life1 = localStorage.getItem("life");
life1=life1-1;
return life1;
}

然后这样调用它们:

  var mainLife;
SetlifeCounter();
mainLife=GetlifeCounter();
while(mainLife!=0)
{

window.location.reload();
}

但是当我运行这个时,页面卡住了......我做错了什么??

P.S 这是为了跟踪编号。每次您在游戏中死亡(页面重新加载)时,游戏中的生命都会被扣除。

最佳答案

是的,使用 localStorage

使用持久值时,您需要检查是否已保存值(来自用户上次访问),如果是,则使用该值。如果没有,您需要创建一个值并将其设置到存储中,以便在后续访问中使用。

这通常是这样完成的:

var x = null;

// Check to see if there is already a value in localStorage
if(localStorage.getItem("x")){

// Value exists. Get it assign it:
x = localStorage.getItem("x");

} else {

// Value doesn't exist. Set it locally and store it for future visits
x = 3.14;
x = Math.floor(x);

localStorage.setItem("x", x);

}

在您的示例中,您遇到了各种问题,但浏览器锁定是由于 while 循环造成的,每当生命计数不为零时,该循环就会创建无限循环。您必须非常小心 while 循环,并确保它们始终有一个会被命中的终止条件。但是,就您的目的而言,这无论如何都是不必要的。

有关正确使用 localStorage 的详细信息,请参阅下面的内嵌注释。

注意:由于沙箱的原因,此代码在 Stack Overflow 代码片段编辑器中无法工作,但您可以看到此工作示例 here

// This is where you will store the lives remaining
// You don't need several variables to keep track of this
// (mainLife, life, life1). Just modify this one variable as needed.
var lifeCount = null;

// As soon as the user arrives at the page, get or set the life count
window.addEventListener("DOMContentLoaded", initLifeCount);

// By convention use camelCase for identifier names that aren't constructors
// and put opening curly brace on same line as declaration
function initLifeCount() {

// You need to test to see if an item exists in localStorage before getting it
if(localStorage.getItem("life")){

// And, remember that localStorage values are stored as strings, so you must
// convert them to numbers before doing math with them.
lifeCount = parseInt(localStorage.getItem("life"), 10) - 1;

// Test to see if there are any lives left
if(lifeCount === 0){
// Invoke "Game Over" code
alert("Game Over!");
}

} else {
// User hasn't previously stored a count, so they must be starting a new game
lifeCount = 3;
}

// Any time the count changes, remember to update it in localStorage
updateLifeCount();

// Temporary code for debugging:
console.log("Life count is: " + lifeCount);
}

// Call this function after the life count changes during game play
function updateLifeCount(){
localStorage.setItem("life", lifeCount)
}

如果您打开开发人员工具 (F12) 并导航到查看 localStorage,您将能够在每次重新运行 Fiddle 时看到该值的减少。您还可以在控制台中看到该值。

enter image description here

enter image description here

关于javascript - 在 JAVASCRIPT 中重新加载页面时保存变量的当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982790/

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