使用moment.js和setInterval的动态日期和时间 [英] Dynamic date and time with moment.js and setInterval
本文介绍了使用moment.js和setInterval的动态日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 moment.js 了解如何显示动态日期和时间。
I'm trying to find out how I can display dynamic date and time using moment.js.
显然我无法理解正确使用setInterval。
Apparently I can't figure out to use setInterval properly.
如果可能,我宁愿不使用jQuery作为时刻.js不需要它。
If possible I'd prefer not to use jQuery as moment.js dosn't need it.
这是我到目前为止所拥有的: http://jsfiddle.net/37fLF/2/ 。
Here's what I have so far: http://jsfiddle.net/37fLF/2/.
$(document).ready(function () {
var datetime = $('#datetime'),
date = moment(new Date()),
update = function(){
datetime.html(date.format('dddd, MMMM Do YYYY, h:mm:ss a'));
};
update();
setInterval(update, 1000);
});
推荐答案
我做过您的代码中的一些修改:
I've made a few modifications in your code:
请注意,方法更新现在在 ready
事件处理程序之外
Note that the method update is now outside the ready
event handler
代码:
var datetime = null,
date = null;
var update = function () {
date = moment(new Date())
datetime.html(date.format('dddd, MMMM Do YYYY, h:mm:ss a'));
};
$(document).ready(function(){
datetime = $('#datetime')
update();
setInterval(update, 1000);
});
这篇关于使用moment.js和setInterval的动态日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文