1

我有一个 div,其中包含可变数量的文本。div 有一个设定的高度,如果文本超过该高度,我想创建一个“阅​​读更多”链接。

我可以计算带有 div 的文本的长度,例如:

$(".longdesc").each(function() {
    var count = $(this).text().length
    console.log(count); 

    if(count > 100){
      //Replace additional characters with " ...Read More"
    };

});

但我不确定如何用“...阅读更多”替换第 100 个字符之后的所有字符。

有人知道该怎么做吗?

4

5 回答 5

3
if(count > 100){
    $(this).text($(this).text().substring(0, 100) + " ...Read More");
};
于 2013-08-22T02:49:10.010 回答
1
if (count > 100) {
    $(this).text($(this).text().substring(0, 100) + ' ...Read More');
}
于 2013-08-22T02:49:16.327 回答
0

使用切片:

text = text.slice(0, 100) + (text.slice(100)? "... Read More" : "");
于 2013-08-22T03:03:42.377 回答
0

尝试

$(".longdesc").text(function(idx, text) {
    return text.length > 100 ? text.substring(0, 100) + '...Read More' : text;
});

如果你想要一个链接

$(".longdesc").html(function(idx, html) {
    return html.length > 100 ? html.substring(0, 100) + '<a href="#">...Read More</a>' : html;
});
于 2013-08-22T02:50:07.573 回答
0

您可以像这样更新整个 HTML div

if (count > 100){
    var newText = $(this).text().substring(0,100);
    newText += "<a href='#'>Read More</a>";
    $(this).html(newText);
}
于 2013-08-22T02:50:18.300 回答