任何可以自动更新页面所有帖子时间的jquery插件 [英] Any jquery plugin which automatic update time for all the posts of a page

查看:47
本文介绍了任何可以自动更新页面所有帖子时间的jquery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有很多帖子,显示发布时间.我想在每1分钟之后继续更新该时间.一种简单的方法是给他们一个相同的类,并在1分钟后获取所有元素并更新时间.任何更好的解决方案.

I have a page having lots of posts showing time when they were posted. I want to keep on updating that time after every 1 min. One simple way can be give them a same class and get all the elements after 1 min and update the time. Any better solutions.

推荐答案

您可以使用像这样的简单插件:

You can use a simple plugin like this:

$.fn.UpdateSince = function(interval) {

    var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });

    var format = function(t) {
        if (t > 60) {
            return Math.floor(t / 60) + ' minutes ago'
        } else {
            return t + ' seconds ago';
        }
    }

    var update = function(){
        var now = new Date().getTime();
        $.each(times, function(i, o){
            o.e.html(format(Math.round((now - o.t) / 1000)));
        });
    };

    window.setInterval(update, interval);
    update();

    return this;
}

它设置了一个以一定间隔运行的函数,并更新了您指定的元素.元素最初包含整数格式的时间,即从1970-01-01开始的毫秒数:

It sets up a function that runs at an interval and updates the elements that you specify. The elements originally contain the time in integer format, i.e. milliseconds since 1970-01-01:

<div class="TimeSince">1314952218779</div>

用法:

$('.TimeSince').UpdateSince(1000);

该参数是更新间隔(以毫秒为单位). 1000是每秒一次,因此,如果以分钟为单位显示时间,则将使用较大的值,例如每20秒或20 * 1000.

The parameter is the update interval in milliseconds. 1000 is once a second, so if you display the time in minutes you would use a larger value, for example every 20 seconds, or 20 * 1000.

您要改进的部分是功能format,它将秒转换为人类可读的格式.现在已经是几分钟和几秒钟了,但是您可能想要几天,几小时或几分钟前的事情.

The part you would want to improve is the function format, which turns seconds into a human readable format. It now has minutes and seconds ago, but you probably want something like, days, hours or minutes ago.

演示: http://jsfiddle.net/Guffa/7EsAX/

这篇关于任何可以自动更新页面所有帖子时间的jquery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆