How do you show the current time on a web page?

时间秒杀一切 提交于 2019-12-13 15:15:25

问题


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?


回答1:


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);

}());


来源:https://stackoverflow.com/questions/28415178/how-do-you-show-the-current-time-on-a-web-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!