即使点击,也会永久显示计数器

时间:2015-10-23 16:32:20

标签: javascript html local-storage counter

我有以下代码:

<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>

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

2 个答案:

答案 0 :(得分:2)

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

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

这使得你的价值在刷新时就会存在。

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

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

工作小提琴here

答案 1 :(得分:1)

你可以试试这个:

将onload添加到正文

<body onload="showCounter();">

并添加此功能:

function showCounter(){
    document.getElementById("result").innerHTML = localStorage.clickcount;
}

它在这里工作 https://jsfiddle.net/7qoqd7k9/