0

長いテキストにさらにリンクを表示するように設定する関数があります。ページの読み込み前に存在する要素ではうまく機能しますが、動的に追加された要素では機能しません。要素を追加した後に short() 関数を呼び出すと、新しく追加された要素でのみ機能しますしかし、ロード前に存在し、機能していた要素は機能しません....以下は私のコードで、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


});
4

1 に答える 1

0

「追加」リンクをクリックするたびに、すべての要素で「短縮」機能を実行しているように見えます。これにより、ハンドラーがボディに複数回.readmoreアタッチされます。click

[追加] リンクが最初にクリックされると、段落が追加され、クリック ハンドラーが 2 回 (2 つの段落ごとに 1 回) 追加されます。[もっと見る] リンクをクリックすると、ハンドラーが 2 回実行されます。クリック ハンドラーが 2 回クリックされると、別の段落が追加され、クリック ハンドラーがさらに 3 回追加されます。[もっと見る] リンクをクリックすると、ハンドラーが 5 回実行されます。次に「追加」リンクがクリックされると、別の段落が追加され、クリック ハンドラーが本文にさらに 4 回追加されます。[See More] リンクをクリックすると、ハンドラーが 9 回実行されます。等々。

jQuery('body').on('click'...)呼び出しは関数の外に移動する必要があると思いshortenます。また、jQuery('.readmore').shorten();に変更する必要があるかもしれませんjQuery('.addElem .readmore:last').shorten();。これによりclick、「See More」リンクのハンドラーが 1 回だけアタッチさshortenれ、各リンクに対してメソッドが 1 回だけ呼び出され.readmoreます。

于 2013-04-05T17:21:02.087 に答える