您如何在网页上显示当前时间? [英] How do you show the current time on a web page?

查看:534
本文介绍了您如何在网页上显示当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我正在上课的网站上显示当前时间,但是我找不到办法。他们有办法显示实时代码吗?

I want to show the current time on a website I am making for class, but I cannot find a way to do so. Is their a way to show real time in code? and if so, how do you do it?

推荐答案

您可以通过首先创建一个元素来轻松完成此操作:

You can accomplish this fairly easily by first creating an element:

<span id="clock"></span>

然后获取对该元素的引用:

And then getting a reference to that element:

var clockElement = document.getElementById( "clock" );

接下来,我们需要一个函数,该函数将随着时间更新内容:

Next we'll need a function that will update the contents with the time:

function updateClock ( clock ) {
    clock.innerHTML = new Date().toLocaleTimeString();
}

最后,我们要确保每秒调用一次保持时钟最新:

Lastly, we'll want to make sure we're calling this every second to keep the clock up to date:

setInterval(function () {
    updateClock( clockElement );
}, 1000);

因此,当我们将它们放在一起时,它看起来像这样:

So when we put it all together it looks like this:

(function () {

  var clockElement = document.getElementById( "clock" );

  function updateClock ( clock ) {
    clock.innerHTML = new Date().toLocaleTimeString();
  }

  setInterval(function () {
      updateClock( clockElement );
  }, 1000);

}());

这篇关于您如何在网页上显示当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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