Activate timeago on newly added elements only

2019-04-15 16:37发布

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);
    }

any ideas?

2条回答
唯我独甜
2楼-- · 2019-04-15 17:14

ok this seems to work

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

Thanks to eddiemonge on #jquery

查看更多
Emotional °昔
3楼-- · 2019-04-15 17:30

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');   
        }
    });
}

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

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

edit just 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);
}

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.

查看更多
登录 后发表回答