【问题标题】:Why current time displayed with JavaScript is not updating without reloading page?为什么在不重新加载页面的情况下使用 JavaScript 显示的当前时间不会更新?
【发布时间】:2019-01-15 00:29:31
【问题描述】:

在我的网站上,我希望实时显示时间并自动更新,而无需刷新页面。

我在 index.php 的标头中有以下内容:

<script src="/../scripts/time.js"></script>

time.js 是下面的脚本:

var currentTime = new Date(),
      hours = currentTime.getHours(),
      minutes = currentTime.getMinutes();
    if (minutes < 10) {
     minutes = "0" + minutes;
  }
    document.write(hours + ":" + minutes)

它确实正确显示了当前时间,但如果不刷新/重新加载网页,它就不会更新。我相信它实际上应该自动更新,因为它是在 JavaScript 中(已知能够这样做)。

我可能做错了什么?

【问题讨论】:

标签: javascript time refresh live


【解决方案1】:

您只使用了一次 currentTime。你必须通过“间隔”来获得它们。这是取自w3schools.com: Window clearInterval() Method的示例代码:

<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
  clearInterval(myVar);
}
</script>

</body>
</html>

请参阅running code here

注意:特意给出了clearInterval()的例子,让理解更进一步。

【讨论】:

  • 感谢这工作!我只是从 w3schools 的“Tryit Editior”复制了那个脚本,它现在可以工作了!
猜你喜欢
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2010-12-22
相关资源
最近更新 更多