繁体   English   中英

如何使用 JavaScript 在页面刷新时保持本地存储值?

[英]How to keep local storage value on page refresh using JavaScript?

我正在尝试使用 HTML 和 JavaScript 创建一个点击计数器,我想在刷新页面后保留数字的值。

我明白我必须为此使用本地存储的事实,并且我已经设法存储该值并在页面刷新后显示它,但是当我再次单击该按钮时,它从 0 开始计数,我不知道如何来解决这个问题。 我希望它保留值并继续计数,即使页面刷新。

HTML代码:

   <div>
      <p id="display">0</p>
      <button onclick="increase()">increase</button>
      <button onclick="decrease()">decrease</button>
    </div>

JavaScript 代码:

let display=document.getElementById("display")
    let count = 0
    
    function increase(){
        count=count+1
        display.textContent=count
        localStorage.setItem("count", JSON.stringify(count))
        
    }
    display.textContent=localStorage.getItem("count")
    
    
    
    function decrease(){
        count=count-1
        display.textContent=count
    }
let display=document.getElementById("display");
    

让 count = localStorage.getItem("count") ? +localStorage.getItem("count") : 0;

    function increase(){
        count=count+1
        display.textContent=count
        localStorage.setItem("count", JSON.stringify(count))
        
    }
    display.textContent=localStorage.getItem("count")
    
    
    
    function decrease(){
        count=count-1
        display.textContent=count
    }

试试上面的片段。

let display=document.getElementById("display")
let count = Number(localStorage.getItem("count")) // here

function increase(){
    count=count+1
    display.textContent=count
    localStorage.setItem("count", JSON.stringify(count))
    
}
display.textContent = count // and here



function decrease(){
    count=count-1
    display.textContent=count
}

我更新了两行注释的代码。

您必须首先使用localStorage值设置count变量。

当窗口加载从本地存储获取计数值并在显示该计数值之后初始化计数变量

const display = document.getElementById("display");

let count = 0;

window.onload = () => {
  count = localStorage.getItem("count")
    ? JSON.parse(localStorage.getItem("count"))
    : 0;
  display.textContent = count;
};

function increase() {
  count = count + 1;
  display.textContent = count;
  localStorage.setItem("count", JSON.stringify(count));
}

function decrease() {
  count = count - 1;
  display.textContent = count;
  localStorage.setItem("count", JSON.stringify(count));
}

暂无
暂无

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

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