【问题标题】:How to make a javascript count up, such as world population? [closed]如何使javascript计数,例如世界人口? [关闭]
【发布时间】:2015-09-18 01:51:37
【问题描述】:

我不知道如何使与实时相关的 Javascript 计数,这意味着当您重新加载页面时,计数器不会重新开始。有人能告诉我如何做到这一点吗:) 像http://www.worldometers.info/ 这样的例子非常感谢。

【问题讨论】:

  • 您需要存储数据,首先想到的是将其存储在数据库中。
  • 看看他们的代码,就在你眼前

标签: javascript html css


【解决方案1】:

他们使用的代码很可能是从数据库中提取的,实际价值在不断增加。

看看这个js fiddle 我做了一个简单的计时器如何工作的例子。请注意,如果您多次按“运行”,时间本身将保持不变。

使用远程数据库会导致更多工作,但要在浏览器刷新时保存值,您应该了解 localStorage 我会查看 W3 School's article 的主题。

在我的实现中我使用

localStorage.setItem("time", currentTime);   // Note that CurrentTime must be a string!

在设置currentTime var 之后的代码的每次迭代中。

当你启动你的应用程序时,一个简单的if 声明

if (localStorage.getItem("time") {
    CurrentTime = localStorage.getItem("time");
} else {
    // set default values
}

会起作用,因为如果值不存在,localStorage.getItem 将返回 null(或者如果您手动将值设置为 null)。

(对于 localStorage,您也可以使用 [bracket notation],并且可能会在最常见的示例中看到)

localStorage["foo"] = "value"; 
// is the same as: 
localStorage.setItem("foo", "value")
// and
var bar = localStorage["foo"]; 
// is the same as: 
var bar = localStorage.getItem("foo");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-23
    • 2012-03-21
    • 1970-01-01
    • 2011-03-26
    • 2012-03-27
    • 2010-09-13
    • 2011-01-15
    • 2018-05-13
    相关资源
    最近更新 更多