首先,抱歉英语不好,因为它不是我的主要语言。
我在使用 Javascript 时遇到了一些问题。几分钟后,某个文件不断使我的浏览器崩溃(无论是 Chrome、Firefox 还是 IE)。
$().ready(function() {
timeAgo();
});
function timeAgo() {
$('time.time-ago').each(function() {
//Get datetime from the attribute
var ago = $(this).attr('datetime');
//Split it so we can convert it to a Date object as Firefox doesn't allow raw input
var spl = ago.split(' ');
var date = spl[0].split('-');
var time = spl[1].split(':');
//Convert to object
ago = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
//Get current date
var now = new Date();
//Calculate difference in days
var days = dayYear(now) - dayYear(ago);
if(days < 0) days += 365;
var out = '';
//Get the propper string
if(days > 0) {
if(days == 1) {
out = 'Gisteren';
}else if(days < 7) {
out = days +' dagen geleden';
}else if(days < 14) {
out = 'Een week geleden';
}else{
out = ago.toLocaleDateString('nl-nl',{day: "numeric",month: "short",year: "numeric"});
}
}else{
var dif = Math.round((now - ago)/1000);
if(dif < 10) {
out = 'Zojuist';
}else if(dif < 60) {
out = 'Enkele seconden geleden';
}else if(dif < 120) {
out = 'Een minuut geleden';
}else if(dif < 60 * 60) {
out = Math.floor(dif/60)+' minuten geleden';
}else if(dif < 60 * 60 * 2) {
out = 'Een uur geleden';
}else{
out = Math.floor(dif/60/60)+' uur geleden';
}
}
$(this).html(out);
});
setInterval(function(){timeAgo()},10000);
}
function dayYear(now) {
var first = new Date(now.getFullYear(),0,1);
var day = Math.round(((now - first) / 1000 / 60 / 60 /24) + 0.5);
return day;
}
例如,我用以下代码调用它。
<time datetime="2013-05-12 19:12:15"></time>
提前致谢。