1

我正在尝试解决不对已经拥有它的元素重复 timeago 函数,而是将其添加到没有它的元素的问题。我正在尝试这个,但新添加的缩写没有被激活

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

有任何想法吗?

4

2 回答 2

2

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

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

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

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

编辑 以免混淆,$('#container .new')选择器不是默认的 jQuery,new是一个像任何其他类一样的 css 类,您可以在new执行 ajaxcall 时将该类添加到您的元素中,或者您可以以其他方式选择它们,因为您可能有只需将它们添加到您的 ajax 回调中的 DOM,您可能已经在数组中提供了它们... 结束编辑

但是,如果你真的想在间隔部分继续使用这个:

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

这个函数你只会在页面加载时调用一次,选项二的缺点,它们不会立即变成 timeago,但只有在下一次间隔命中之后。

于 2011-09-15T19:32:49.287 回答
0

好的,这似乎有效

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

感谢 #jquery 上的 eddiemonge

于 2011-09-15T19:29:11.807 回答