javascript - 如何定期更新时间?

标签 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>

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

最佳答案

您的代码中有许多错误。如果不在变量声明前使用 var,就会将它们泄漏到全局范围内。

另外,document.write的使用是discouraged .

这是我的做法:

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

HTML:

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

关于javascript - 如何定期更新时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091888/

相关文章:

javascript - 使用管道删除 Angular2 中的锐音符号

javascript - 从前端 fetch() 请求调用时,Express res.redirect() 不重定向浏览器 URL

javascript - 元素不会根据变量值和 if 语句显示()

javascript - JavaScript 中的对象歧义

python - Pandas 本地化和转换日期时间列而不是日期时间索引

c# - 日期时间本地化。任何标准/最佳实践

javascript - 计算可预订资源的可用时段

javascript - 如何在 Javascript 中启动 php session ?

javascript - 从数组中生成 n 组唯一对

javascript - 模拟不同div的点击