如何定期更新时间?

ale*_*lex 15 javascript jquery datetime

function timeClock()
{
    setTimeout("timeClock()", 1000);        
    now = new Date();
    alert(now);
    f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
    return f_date;
}

<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
Run Code Online (Sandbox Code Playgroud)

警报(现在的); 每秒给我一个值,但它没有在html中更新.如何在不刷新页面的情况下更新html的时间?

Ivo*_*zel 36

您的代码中存在许多错误.如果不使用var变量声明的infront,则将它们泄漏到全局范围中.

此外,使用的document.write鼓励.

我是这样做的:

JavaScript的:

function updateClock() {
    var now = new Date(), // current date
        months = ['January', 'February', '...']; // you get the idea
        time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea

        // a cleaner way than string concatenation
        date = [now.getDate(), 
                months[now.getMonth()],
                now.getFullYear()].join(' ');

    // set the content of the element with the ID time to the formatted string
    document.getElementById('time').innerHTML = [date, time].join(' / ');

    // call this function again in 1000ms
    setTimeout(updateClock, 1000);
}
updateClock(); // initial call
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="time"> </div>
Run Code Online (Sandbox Code Playgroud)


小智 5

setInterval(expression,timeout);

函数setTimeout用于单个超时,因此使用setInterval将是一个更合适的选项。SetInterval将正常运行,而不会出现Ivo的答案的其他行。

我将重写Ivo的答案,如下所示:

JavaScript:

function updateClock() {
  // Ivo's content to create the date.
  document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Run Code Online (Sandbox Code Playgroud)

自己尝试一下!https://jsfiddle.net/avotre/rtuna4x7/2/