省略号修剪段落的setInterval函数

时间:2014-02-28 16:01:57

标签: javascript jquery-isotope

我有一个关于修剪段落并在同位素内每个修剪段落的末尾添加省略号的问题。来自同位素的内容。我们也使用无限滚动。问题是省略号函数在页面加载时已经存在于DOM中的内容上工作正常,但是当从无限滚动加载新内容时,省略号函数将不适用于新段落。

我的解决方案是在函数上使用setInterval来每秒运行一次,这样就可以接受它每次运行时都会为它添加更多点阵点。我想做的是每次间隔运行时都能清空...。至少我认为这是一个答案。我只是不知道如何实现它。我的代码如下,任何建议都将受到赞赏:

var myVar = setInterval(function () {
    trim();
}, 500);

function trim() {
    var MORE = "...";
    $(".gallery .spotProfile p.trim-ellipsis").each(function () {
        var $ths = $(this),
            txt = $ths.text();

        // Clear the text
        $ths.text("");

        // First 100 chars
        $ths.append( $("<span>").text( txt.substr(0, 80) ) );

        // The rest
        $ths.append( $("<span>").text( txt.substr(80, txt.length) ).hide() );

        // More link
        $ths.append(
        $("<a class=trimmed>").text(MORE).click(function () {
            var $ths = $(this);
            $ths.prev().hide();
            // more.empty();
            $ths.text(MORE);
        }));
    });
}

1 个答案:

答案 0 :(得分:2)

这很简单。

$(".gallery .spotProfile p.trim-ellipsis").each(function(){
    var $ths = $(this),
        txt = $ths.text();

    if( $ths.find('.trimmed')[0] ) return;

检查元素是否具有修剪元素并返回(继续下一个循环)