在我的网站上,我有一个评论表,它会告诉您评论是在多长时间前发布的。
下面的代码每 10 秒仅重新加载包含日期的范围,不是整个评论 div(以防止页面滞后)
$(function(){
setInterval(
function(){
var id = $('.date').html();
$('.date').load('/comdate.php?id=' + id); }
,10000);
});
我的函数不起作用,我真的不想为每个评论的日期字段创建一个单独的函数。请有人指出我的问题吗?谢谢
编辑
我在 javascript 中使用它来将时间更改为可读日期
function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
jQuery.fn.prettyDate = function(){
return this.each(function(){
var date = prettyDate(this.title);
if ( date )
jQuery(this).text( date );
});
};
虽然这会返回 GMT+1,因为那是我所在的位置。我如何更改此函数以使 javascript 时区也成为 GMT?
最佳答案
对我来说,我会更改我的 ajax 请求以仅发送一次 unix 时间跨度,并且我会使用 javascript 进行所有计算。
var periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"];
var lengths = ["60","60","24","7","4.35","12","10"];
function nicetime(user_date)
{
if(typeof user_date == "undefined" ) {
return "No date provided";
}
var now = new Date().getTime();
var unix_date = user_date;
// check validity of date
if(unix_date == "") {
return "Bad date";
}
// is it future date or past date
if(now > unix_date) {
var difference = now - unix_date;
var tense = "ago";
} else {
var difference = unix_date - now;
var tense = "from now";
}
difference = difference/1000; //from milliseconds to seconds;
for(var j = 0; difference >= lengths[j] && j < lengths.length-1; j++) {
difference /= lengths[j];
}
difference = Math.round(difference);
if(difference != 1) {
periods[j] += "s";
}
return difference+" "+periods[j]+" "+tense;
}
console.log(nicetime(1378632182334));
例子:
注意 我在你的函数中唯一改变的是:
difference = difference/1000; //from milliseconds to seconds;
您的代码以毫秒为单位处理差异变量,本应以秒为单位。
关于javascript - 使用 jQuery,我如何将文本 ajax 加载到多个 .classes 而不是 #id 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682121/