在javascript中制作一个实时时钟 [英] Making a live clock in javascript

查看:113
本文介绍了在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 = h + ":" + m + ":" + s;
}

setInterval(time, 1000);

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

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

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