Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用setInterval方法时MomentJS不工作_Javascript_Momentjs - Fatal编程技术网

Javascript 使用setInterval方法时MomentJS不工作

Javascript 使用setInterval方法时MomentJS不工作,javascript,momentjs,Javascript,Momentjs,我正在使用moment.js将时间戳转换为可读形式,就像8分钟前一样 我使用setInterval每1秒更新一次代码以动态更新时间,但它根本不起作用。救救我 代码: 让计时器==>{ 让time=document.getElementsByClassName'timeago'; forlet i=0;i{ timeagoSpan.textContent=from.fromNow; }; 定时器; setIntervaltimer,1000; 2018-05-14 22:21:00 在您第一次更

我正在使用moment.js将时间戳转换为可读形式,就像8分钟前一样

我使用setInterval每1秒更新一次代码以动态更新时间,但它根本不起作用。救救我

代码:

让计时器==>{ 让time=document.getElementsByClassName'timeago'; forlet i=0;i您正在将元素的文本解析为字符串,并告诉moment每次函数运行时都要根据YYYY-MM-DD h:MM:ss对其进行解释。相反,只保存一次该时刻,每隔一段时间,计算它与现在的差值

您还需要询问时刻以正确设置格式。您的元素有09:21:00,但矩格式字符串是h:mm:ss-这在两位数小时的情况下不起作用

const timeagoSpan=document.querySelector'.timeago'; const from=momenttimeagoSpan.textContent,YYYY-MM-DD hh:MM:ss; 让计时器==>{ timeagoSpan.textContent=from.fromNow; }; 定时器; setIntervaltimer,1000; 2018-05-14 22:21:00
在您第一次更新元素的innerText之后,您希望如何在下一次迭代中将其解析为YYYY-MM-DD h:MM:ss?噢!明白逻辑了。谢谢,伙计!