阅读更多链接功能,动态添加的元素不起作用

时间:2013-04-05 16:59:45

标签: jquery html function

我有一个函数设置在长文本上看到更多的链接。它适用于页面加载之前存在的元素,但不能动态添加元素,我在添加元素后调用shorten()函数,然后它只适用于新添加的元素,但加载前的元素和工作,不起作用....下面是我的代码,你可以检查jsfiddle here

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


});

1 个答案:

答案 0 :(得分:0)

似乎只要点击“添加”链接,就会在所有.readmore元素上运行“缩短”功能,这会将click处理程序多次附加到正文

第一次单击“添加”链接时,会添加一个段落,并且单击处理程序将添加2次(对于2个段落中的每个段落一次),然后单击“查看更多”链接会导致处理程序运行2次。单击第二次单击处理程序时,将添加另一个段落,并再次添加单击处理程序3次,并单击“查看更多”链接将导致处理程序运行5次。下次单击“添加”链接时,会添加另一个段落,并且单击处理程序将多次添加到正文中。单击“查看更多”链接会导致处理程序运行9次。等等。

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