[英]Limit characters via jquery
我有一個div,顯示的是一堆文本,但我只希望顯示75個字符,其余的文本替換為...
<div class="text-info">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation</div>
$('text-info').replaceWith(this).length(75 + "...");
var text = $(".text-info").text();
var len = text.length;
if(len > 75){
$(".text-info").text($(".text-info").text().substr(0,74)+'... ');
}
從字面上回答您的問題,如果只希望顯示75個字符,則可以簡單地用作@MohammadAdil指示符。 但是,您最終將獲得79個字符(74 + 3(...)+兩個空格。只需拉出72個字符並附加"..."
即可限制該字符,當然如果您實際上需要將該限制75個可見字符,或者如果您只想表示帖子的75個字符,然后添加省略號。
我個人的建議是將其留給一個可以為您做的庫(或盡可能使用一個)。 Underscore是一個很小的庫,其中包含許多方便的實用程序,它負責確定是否可以內置及其實現(例如_.each
如果已定義, _.each
使用Array#forEach
)。 話雖這么說, underscore.string是下划線的附加組件,其中包含許多有用的字符串操作函數,例如_.toSentence
,它們將采用["one", "two", "three"]
和數組的形式["one", "two", "three"]
並返回"one, two and three"
但更重要的是,您會truncate
和prune
。
truncate
和prune
僅在字符串達到極限時才執行截斷,例如:
// Assume the underscore.string functions have bene mixed into _
_.truncate("Hello, World", 5) // "Hello..."
_.truncate("Hello", 10) // "Hello"
truncate
功能將剪切文本中間的句子,這是prune
的一種更簡潔的選擇,因為它會將最接近的分詞符處的文本切成指定的長度。 以他們的例子為例:
_.prune("Hello, cruel world", 15) // "Hello, cruel..."
// for comparison
_.truncate("Hello, cruel world", 15) // "Hello, cruel wo..."
這樣的事情會起作用:
(".text-info").text($(this).text().substr(0, 75)+'...');
另外,不要忘記選擇器中的類標識符。 .
你可以試試這個
$(".text-info").text(function(){
return $(this).text().length > 75 ? $(this).text().substr(0, 75)+'...' : $(this).text();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.