本文介绍了仅在新添加的元素上激活timeago的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决以下问题:不对已经具有timeago函数的元素重复执行timeago函数,而是将其添加到不具有timeago函数的元素中.我正在尝试这种方法,但是新添加的abbrs没有被激活

I'm trying to fix the problem of not repeating the timeago function to elements that have it already, but adding it to the ones that don't have it. I'm trying this but newly added abbrs are not getting activated

<abbr title="2011-09-15T12:46:26" class="timeago">less than a minute ago</abbr>


function activate_timeago(){
        setInterval(function(){
            $('.timeago').each(function(){
                if ($(this).data('active')!='yes'){
                    $(this).timeago();
                    $(this).data('active','yes');
                }
            });
        },60000);
    }

有什么想法吗?

推荐答案

我不会像您尝试的那样以一定的间隔激活它们,而是在创建新项目时立即激活,只需调用一个像这样的函数

i would not activate them with an interval like you are trying, but rather immediately when creating the new item, just call a function like this one

function activate_timeago(el){
    $(el).each(function(){
        if (!$(this).hasClass('processed')){
            $(this).timeago();
            $(this).addClass('processed');
        }
    });
}

用于获取新项目的ajax回调完成后,只需调用:

after the ajax callback for fetching new items is done, just call:

var elements = $('#container .new');
activate_timeago(elements);

修改只是为了没有混淆,$('#container .new')选择器不是默认的jQuery,new是与其他任何类一样的CSS类,可以在执行ajaxcall时将new类添加到元素中,或者可以选择因为您可能刚刚将它们添加到了ajax回调中的DOM中,所以它们可能已经在数组中可用了……结束编辑

editjust so there is no confusion, the $('#container .new') selector is not default jQuery, new is a css class like any other class, you could add the class new to your elements when you do the ajaxcall, or you could select them in another way since you probably have just added them to the DOM in your ajax callback you already might have them available in an array ...end edit

但是,如果您真的想继续执行间隔部分,请使用以下命令:

but,if you really want to continue on the interval part use this:

function activate_timeago(){
    setInterval(function(){
        $('.timeago:not(.processed)').each(function(){
                $(this).timeago();
                $(this).addClass('processed');
            }
        });
    },60000);
}

您只需在页面加载时调用一次此函数,选项2的缺点是,它们不会立即变成timeago,而只有在下一次间隔到达时才会变成timeago.

this function you'd only call once at the page load,downside of option two, they are not made into timeago immediately, but only after the next time the interval hits.

这篇关于仅在新添加的元素上激活timeago的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 00:47