如何用Javascript更改当前时间

问题描述 投票:1回答:3

我想在我的网页上显示当前时间。当我推动F5,我可以得到时间,但它没有改变。帮我..

HTML

      <div id="time" class="timer">
          show_time
       </div>

使用Javascript

var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
   dn="AM";
if (hours>12)
   hours=hours-12;
if (hours==0)
   hours=12;
if (minutes<=9)
   minutes="0"+minutes;
if (seconds<=9)
   seconds="0"+seconds;
setInterval(setTime, 1000);
function setTime(){
    text2.innerHTML ="현재 시간: <br>"+ hours + ':' + 
    minutes + ':' + seconds+ "<bn>"+dn;
 }

setTime();

谢谢!

javascript html
3个回答
2
投票

试试这个

const el = document.getElementById('nav-time');

function updateClock() {
   var now = new Date();
   var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(); 
        
   el.innerHTML = time;    
}

setInterval(updateClock, 1);
<li><span id="nav-time">Clock
<span class="divider"> | </span>

0
投票
function setTime(){
    document.getElementById("time").innerHTML ="현재 시간: <br>"+ hours + ':' + 
    minutes + ':' + seconds+ "<bn>"+dn;
 }

您必须在当前代码中添加一些内容,以便setTime函数实际将其输出添加到DOM。我使用document.getElementById("time")将函数的时间添加到页面中。


0
投票

您需要获取函数内的当前时间,否则它将返回在第一次调用函数时获得的值

function setTime(){

var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
 dn="AM";
if (hours>12)
 hours=hours-12;
if (hours==0)
 hours=12;
if (minutes<=9)
 minutes="0"+minutes;
if (seconds<=9)
 seconds="0"+seconds;

  text2.innerHTML ="현재 시간: <br>"+ hours + ':' + 
  minutes + ':' + seconds+ "<bn>"+dn;
}

setTime();

setInterval(setTime, 1000);

https://jsfiddle.net/1gc8ymkd/

© www.soinside.com 2019 - 2024. All rights reserved.