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