【问题标题】:Javascript function to count button click?Javascript函数来计算按钮点击?
【发布时间】:2016-12-05 06:02:12
【问题描述】:

我有 JavaScript 代码来计算按钮点击次数。但是在重新加载页面时计数器设置为零。

是否有任何解决方案来计算按钮点击次数,并在页面重新加载时保持该变量值?

var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
// Line commented out as SO does not allow it
// window.localStorage.setItem("on_load_counter", count);
button.onclick = function() {
  count++;
  display.innerHTML = count;
}
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>

【问题讨论】:

  • 您可以将计数器保存在 cookie 或 HTML5 存储中\
  • 对 Satpal 使用会话存储或本地存储是正确的
  • 伙计们,他的代码var count = 0;这里有一个小错误

标签: javascript button count reload


【解决方案1】:

使用变量localStorage.clickcount,您可以在每次点击时递增。

看到这个jsfiddle

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多