[英]How to keep local storage value on page refresh using JavaScript?
I am trying to create a click counter using HTML & JavaScript and I want to retain the value of the number after the page is refreshed.我正在尝试使用 HTML 和 JavaScript 创建一个点击计数器,我想在刷新页面后保留数字的值。
I understand the fact that I have to use local storage for that and I have managed to store the value and display it after the page is refreshed but when I click on the button again, it starts the count from 0 and I do not know how to solve this issue.我明白我必须为此使用本地存储的事实,并且我已经设法存储该值并在页面刷新后显示它,但是当我再次单击该按钮时,它从 0 开始计数,我不知道如何来解决这个问题。 I want it to retain the value and continue counting even if the page is refreshed.
我希望它保留值并继续计数,即使页面刷新。
HTML Code: HTML代码:
<div>
<p id="display">0</p>
<button onclick="increase()">increase</button>
<button onclick="decrease()">decrease</button>
</div>
JavaScript Code: 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");
let count = localStorage.getItem("count") ?
让 count = localStorage.getItem("count") ? +localStorage.getItem("count") : 0;
+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
}
try above snippet.试试上面的片段。
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
}
I updated two lines of your code which is commented.我更新了两行注释的代码。
You have to set count
variable first with value from localStorage
.您必须首先使用
localStorage
值设置count
变量。
when window load get the count value from local storage and init the count variable after that display that count value当窗口加载从本地存储获取计数值并在显示该计数值之后初始化计数变量
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.