问题
Fiddle
I am making a social network and when you post something, I want to show the time. I have the current code to display the time (this isn't only the time, it's also validating and posting the text):
$('#b').click(function () {
var v = $('#type').val();
var u = $('#input').val();
if (v !== "" && u !== ""){
var time = new Date();
var currentime = Date.now();
var x = currentime - time;
$("ul").prepend("<li>" + v + "<br />Posted by " + u + " " + x +" minutes ago </li>");
$('#type, #input').css('border','');
}
else if (v == "" && u == "") {
$('#type, #input').css('border','1px solid red');
}
else if (v == "") {
$('#type').css('border','1px solid red');
$('#input').css('border','');
}
else {
$('#input').css('border','1px solid red');
$('#type').css('border','');
}
});
When the time posts, it says 0 minutes ago (like I told it to), but after any amount of time, it still says 0.
回答1:
fiddle
Basically you set up a setInterval which governs ho frequently you update your time attribute. I used a span
with a class .time
to so you could theoretically update anything with time.
I would go further and hash your posts so you can easily retrieve each posts original time.
EDIT: added a new fiddle.
来源:https://stackoverflow.com/questions/20302008/getting-elapsed-time-in-js