我已经测试过了,这很有效:
$(document.body).on('click', 'button', function(){
var id= $(this).data('id'),
comment=$('textarea[data-id="'+id+'"]').val();
var time = new Date();
start_timer = setInterval(function() {
//var time = new Date();
var time2 = time_since(time.getTime()/1000);
$('div[data-id="'+id+'"]').html(time2);
},
1000);
$('#'+id).html(comment);
});
/**
* date_suffix()
* returns the date suffix (st,nd,rd,th) for a given day in a month
*
* @author: Andy Thomas (forrst@antom.co.uk)
* @date: 27/09/2010
*/
function date_suffix(date) {
if (date == 1 || date == 21 || date == 31) {
return 'st';
} else if (date == 2 || date == 22) {
return 'nd';
} else if (date == 3 || date == 23) {
return 'rd';
} else {
return 'th';
}
}
/**
* time_since()
* returns the time passed since a given unix_timestamp.
* eg. 10 seconds ago, 1 hour ago, 10th Sep etc
*
* @author: Andy Thomas (forrst@antom.co.uk)
* @date: 27/09/2010
*/
function time_since(original) {
original = new Date(original * 1000);
var str = '';
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
var chunks = [
[31536000000, 'year'],
[2592000000, 'month'],
[604800000, 'week'],
[86400000, 'day'],
[3600000, 'hour'],
[60000, 'minute'],
[1000, 'second'],
];
var today = new Date();
var since = new Date(today.getTime() - original.getTime());
if (since.getTime() > 604800000) {
str = months[original.getMonth()] + ' ' + original.getDate() + date_suffix(original.getDate());
if (since.getTime() > 31536000000) {
str = str + ', ' + original.getFullYear();
}
return str;
}
var ms = 0;
var name = 0;
var i = 0;
var ic = chunks.length;
var count = 0;
for (i=0;i<ic;i++) {
ms = chunks[i][0];
name = chunks[i][1];
count = Math.floor(since.getTime() / ms);
if (count != 0) {
break;
}
}
return count + ' ' + name + ((count == 1) ? '' : 's') + ' ago';
}