長いテキストにさらにリンクを表示するように設定する関数があります。ページの読み込み前に存在する要素ではうまく機能しますが、動的に追加された要素では機能しません。要素を追加した後に 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 + ' </span><span class="morecontent"><span>' + h + '</span> <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
});