如何使用 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");
        
// Here was a mistake, you don't need to reset counter each time
let 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 变量。

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

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));
}