【问题标题】:Current time on website not displaying correctly网站上的当前时间显示不正确
【发布时间】:2023-04-03 12:33:01
【问题描述】:

所以我得到了新的时间,但不是更新它,它只是一次又一次地在屏幕上写下时间。我研究了如何设置间隔,这就是我发现的方式。我正在尝试学习 html 和 javascript,所以很抱歉不明白如何解决这个问题。

这是我的 html 代码中我从 js 文件中调用它的部分。 Id="time" 是当前时间的 javascript 代码。

    <div id="top">
            <span id="quote"><script type="text/javascript" src="quote.js"></script></span>
            <span id="date"><script type="text/javascript" src="date.js"></script></span>
            <span id="time"><script type="text/javascript" src="time.js"></script></span>
    </div>

这是当时的 javascript 代码。

function time(){
var currentDate = new Date();
var hour = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
var time = hour + ":" + minutes + ":" + seconds;
document.write(time);
}
setInterval(function(){time()},1000);

如您所见,它描绘了时间 1:02 1:03 1:04.......

非常感谢您的帮助!

【问题讨论】:

  • 创建一个可以包含文本的元素,并将此文本替换为您计算的时间。

标签: javascript html date time


【解决方案1】:

首先,没有理由将您的&lt;script&gt; 标签放在&lt;span&gt; 标签中。相反,请将它们放在结束 &lt;/body&gt; 标记之前。

第二,不要使用document.write()更新内容。见:Why is document.write considered a "bad practice"?

这对你有用:

<div id="time"></div>

function time(){
 var currentDate = new Date();
 var hour = currentDate.getHours();
 var minutes = currentDate.getMinutes();
 var seconds = currentDate.getSeconds();
 var time = hour + ":" + minutes + ":" + seconds;

 //get the time div
 var timeDiv = document.getElementById("time");
 timeDiv.innerHTML = time; //set the content of time div to current time
 }
 setInterval(function(){time()},1000);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2018-06-28
    • 1970-01-01
    • 2022-01-10
    • 2015-09-17
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多