gpt4 book ai didi

javascript - 即使在点击时也永久显示计数器

转载 作者:行者123 更新时间:2023-11-30 12:12:48 25 4
gpt4 key购买 nike

我有以下代码:

<body>
<div class="block">
<button onclick="clickCounter()" type="button" class="button">Click me!</button>
<div onload="clickCounter()" id="result"></div>
<button id="reset" class="button">Reset</button>
</div>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}


function reset_counter() {
localStorage.clickcount= 0;
}

document.getElementById('reset').addEventListener('click', reset_counter);
</script>
</body>

当我重新加载页面时,该值会消失,直到我再次单击“单击我”按钮,我希望该值一直保留在屏幕上。任何人都可以修改代码,使单击我按钮只添加到值,并且该值始终显示在屏幕上吗?

最佳答案

将此行添加到脚本底部以在发生任何点击之前初始化结果:

document.getElementById("result").innerHTML = "You have clicked the button " + (localStorage.clickcount || 0) + " time(s).";

这使得您的值(value)将在刷新时存在。

您的重置功能还缺少更新结果的部分:

function reset_counter() {
localStorage.clickcount = 0;
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
}

工作 fiddle here .

关于javascript - 即使在点击时也永久显示计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307307/

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