首先,對於任何不好的英語,由於它不是我的主要語言,所以對不起。瀏覽器在某些Javascript文件上不斷崩潰
我對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>
在此先感謝。
您確定此文件是罪魁禍首嗎?我在Chrome 26中運行你的代碼沒有問題。 – 2013-05-13 21:08:46
你是什麼意思「崩潰」瀏覽器?發生了什麼讓你覺得有什麼不對? – 2013-05-13 21:09:43