如何使JS计数器永久保留计数数? [英] How to make a JS counter permanently retain the number of counts?

查看:32
本文介绍了如何使JS计数器永久保留计数数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在tumblr上制作一个带有按钮的页面,该页面计算被按下的次数.我已经开始使用它了,但是关闭或刷新浏览器会清除值,并且来自不同用户的点击不会叠加.这就是我所拥有的:

I'm trying to make a page on my tumblr that has a button on it, which counts how many times it's been pressed. I've gotten it to work, but a browser close or refresh clears the value, and clicks from different people don't stack. Here's what I have:

<body>
  <div class="main">

    <h3>Click Counter</h3>
    <button id="clickme">Click me: 0</button>

    <h5>Filler Text</h5>

  </div>
  <script>
    var button = document.getElementById("clickme"),
        count = 0;
        
    button.onclick = function() {
      count += 1;
      button.innerHTML = "Click me: " + count;
    };
  </script>
</body>

这会使按钮在按下时计数,但是我希望它的行为像这样:

This makes the button count up when pressed, but I want it to behave like so:

用户#1单击两次.计数器读两个.

User #1 clicks twice. Counter reads two.

用户#2访问该页面,计数器已经是两个,用户单击3次.计数器在5点.

User #2 visits the page, counter is already at two, user clicks 3 times. Counter is at 5.

3号用户访问,他们的计数器仍为5,依此类推.

User #3 visits, counter is still at 5 for them as well, etc.

截至目前,每个用户都访问该页面,并且该值从零开始.帮助吗?

As of right now, each user visits the page and the value starts at zero. Help?

推荐答案

javascript在浏览器上运行,并将所有变量存储在浏览器中,因此变量的作用域在浏览器中.您可以使用本地存储,但是如果所有用户都使用同一个浏览器,而这不是您所需要的,那么持久化数据的唯一方法是将计数(数据)保存到服务器中并在页面加载时获取计数(数据).

javascript runs on the browser and store all the variable in the browser so the scope of a variable is in the browser. you can use local storage but if all user uses the same browser which is not your need so only way to persist data is to save count (data) into the server and fetch count (data) on a load of the page.

如果没有任何服务器,则可以使用 firebase实时数据库.

you can use firebase real-time database if you don't have any server.

入门Web的Firebase实时数据库

这篇关于如何使JS计数器永久保留计数数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆