0

我有一个函数可以在长文本上设置查看更多链接..它适用于页面加载之前存在的元素,但不适用于动态添加的元素,我在添加元素后调用缩短()函数,然后它只适用于新添加的元素但是加载之前存在并且正在工作的元素,不起作用....下面是我的代码,您可以在此处查看 jsfiddle

HTML

    <div class="main">
      <p class="readmore">this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text text this is some text this is some text text this is some text this is some text text this is some text this is some text</p>
    </div>
    <div class="new-elem"></div>
    <a href="#" class="addElem">Add</a>

JS

jQuery.fn.shorten = function (settings) {
var config = {
    showChars: 100,
    ellipsesText: "...",
    moreText: "See More",
    lessText: "See Less"
};

if (settings) {
    jQuery.extend(config, settings);
}

jQuery('body').on('click', '.morelink', function () {
    var his = jQuery(this);
    if (his.hasClass('less')) {
        his.removeClass('less');
        his.html(config.moreText);
    } else {
        his.addClass('less');
        his.html(config.lessText);
    }
    his.parent().prev().toggle();
    his.prev().toggle();

    return false;
});

return this.each(function () {
    var his = jQuery(this);

    var content = his.html();
    if (content.length > config.showChars) {
        var c = content.substr(0, config.showChars);
        var h = content.substr(config.showChars, content.length - config.showChars);
        var html = c + '<span class="moreellipses">' + config.ellipsesText + '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="javascript://nop/" class="morelink">' + config.moreText + '</a></span>';
        his.html(html);
        jQuery(".morecontent span").hide();
    }
});
}

jQuery('.readmore').shorten();  //for load time

jQuery(document).on('click', '.addElem', function () {
    jQuery('.new-elem').append('<p class="readmore">this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text this is some text</p>');
    jQuery('.readmore').shorten();  //for newly added elements


});
4

1 回答 1

0

似乎每当单击“添加”链接时,您都会在所有元素上运行“缩短”功能,这会将处理程序多次.readmore附加到正文。click

第一次单击“添加”链接时,添加了一个段落,并且单击处理程序添加了 2 次(2 个段落中的每个段落一次),单击“查看更多”链接会导致处理程序运行 2 次。第 2 次单击单击处理程序,添加了另一个段落,并且单击处理程序被添加了 3 次,单击“查看更多”链接导致处理程序运行 5 次。下次单击“添加”链接时,会添加另一个段落,并且单击处理程序会再添加 4 次。单击“查看更多”链接会使处理程序运行 9 次。等等。

我认为jQuery('body').on('click'...)应该将调用移出shorten函数。另外,jQuery('.readmore').shorten();应该改成jQuery('.addElem .readmore:last').shorten();. 这将导致click“查看更多”链接的处理程序仅附加一次,并且将导致shorten每个链接仅调用一次方法.readmore

于 2013-04-05T17:21:02.087 回答