【问题标题】:Display click count and redirect to a url显示点击次数并重定向到 url
【发布时间】:2014-11-20 10:12:15
【问题描述】:

我找到了下面的代码来检查按钮被点击的次数。但是,我希望按钮在单击后重定向到 URL 并更新点击次数。

<html>
  <head>
    <title>Increment count when button is clicked</title>
  </head>

  <body>
    <input type="button" value="Count" id="countButton" />

    <p>The button was pressed <span id="displayCount">0</span> times.</p>

    <script type="text/javascript">
      var count = 0;
      var button = document.getElementById("countButton");
      var display = document.getElementById("displayCount");

      button.onclick = function(){
        count++;
        display.innerHTML = count;
      }
    </script>
  </body>
</html>

【问题讨论】:

  • 是否要将计数保存在数据库中,然后重定向到其他页面?
  • 我想把它存储在cookie或本地存储中。

标签: javascript html click counter url-redirection


【解决方案1】:
button.onclick = function(){
  count++;
  display.innerHTML = count;
  window.location = "http://jonathanmh.com";
}

这可以解决问题,但没有人会看到这个数字,因为它会在用户被重定向到另一个页面后消失。如果您想保存号码以供其他用户查看,则需要将其保存在服务器上,最好保存在数据库中。

【讨论】:

  • 您可以将该号码存储在 cookie 或 localStorage 中 - 无需 db。
  • 如何将数字存储在 cookie 中?
【解决方案2】:

要实现这一点,您需要将点击计数存储在 cookie 或 localStorage(或您的数据保存的任何其他位置)中:

var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");

button.onclick = function(){
    if (isNaN(localStorage.yourCounter))
        localStorage.yourCounter = 0;
    localStorage.yourCounter++;
    display.innerHTML = localStorage.yourCounter;
    window.location = 'http://jsfiddle.net/'
}

【讨论】:

  • 由于某种原因,我无法使用该代码保存 jsfiddle - 当我保存或更新时,它会将我重定向到 jsfiddle.net