简体   繁体   English

如何在 HTML/CSS 中制作计数器

[英]How can I make a counter in HTML/CSS

So I made a button thats suppose to keep track of how many time ANYONE clicked, like a total click counter.所以我做了一个按钮来记录任何人点击了多少次,比如总点击计数器。 But I encounter an issue where when I reload the page, it resets back to 0. I want to make sure that it will count everyones click and save但是我遇到了一个问题,当我重新加载页面时,它会重置为 0。我想确保它会计算每个人的点击并保存

 <script> let num = 0; function myFunction() { document.getElementById("num").textContent = ++num; } </script> <button class="button" onclick="myFunction()"> <p id="num"></p>

You can not do that with browser-based javascript alone.你不能单独使用基于浏览器的 javascript 来做到这一点。 Your website is executed on the client and has no direct way to communicate with other clients.您的网站是在客户端上执行的,无法与其他客户端直接通信。 When you want to have any information in your client-sided javascript which is not available to the client (like who else is accessing the website), then you need to request that information from a server.如果您想在客户端 javascript 中获取任何客户端无法使用的信息(例如还有谁正在访问该网站),那么您需要从服务器请求该信息。

This means you need some form of server-sided programming to log and count page access, store the number on the server and embed that number in the HTML documents being delivered.这意味着您需要某种形式的服务器端编程来记录和计算页面访问、将数字存储在服务器上并将该数字嵌入到正在交付的 HTML 文档中。

The technology options for server-sided web development are countless.服务器端 web 开发的技术选择数不胜数。 Even just listing all the options you have would make this answer far too long.即使只是列出您拥有的所有选项也会使这个答案太长。 So I am not going to give you an example in any particular technology.所以我不会给你举任何特定技术的例子。 Do your own research to get an overview of the technology options available to you and decide which one you would like to learn.进行自己的研究,以了解可供您使用的技术选项的概述,并决定您想学习哪一项。 When you are not sure how to do this in the technology you picked, feel free to ask a new question.当您不确定如何在您选择的技术中做到这一点时,请随时提出一个新问题。

you can save your current state into localstorage您可以将当前的 state 保存到本地存储中

like this像这样

 <script>
    let num = localStorage.getItem("counter");
    function myFunction() {
    document.getElementById("num").textContent = ++num;
    localStorage.setItem("counter", document.getElementById("num").textContent);

  }
  </script>
  
  <button class="button" onclick="myFunction()">
  <p id="num"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM