用javascript制作实时时钟 [英] Making a live clock in javascript

查看:32
本文介绍了用javascript制作实时时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时钟有点工作.但是它不是替换当前的时间,而是每秒打印一个新的时间.我明白它为什么这样做,但我不知道如何解决它.如果您能给我一些提示而不直接说出答案,我将不胜感激.谢谢你.这是我的代码:

The clock kinda works. But instead of replacing the current time of day it prints a new time of day every second. I understand why it do it but I don't know how to fix it. I would appreciate if you could give me some tips without saying the answer straight out. Thank you. Here is my code:

function time(){
    var d = new Date();
    var s = d.getSeconds();
    var m = d.getMinutes();
    var h = d.getHours();
    document.write(h + ":" + m + ":" + s);
}

setInterval(time,1000);

推荐答案

添加 span 元素并更新其文本内容.

Add a span element and update its text content.

var span = document.getElementById('span');

function time() {
  var d = new Date();
  var s = d.getSeconds();
  var m = d.getMinutes();
  var h = d.getHours();
  span.textContent = 
    ("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}

setInterval(time, 1000);

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

答案更新 [2021] https://stackoverflow.com/a/67149791/7942242

这篇关于用javascript制作实时时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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