2010-11-08 53 views
6

我從JSON提要中拉出,我只想顯示最多10個字符的字符串,然後執行...之後的操作。我如何使用JQuery來做到這一點?設置字符數限制以在段落中顯示

+0

您編輯的問題,包括一些你已經寫好,以獲得更多的代碼響應。 +1爲全新用戶拒絕投票而無任何上市原因。 – 2010-11-08 17:21:50

回答

4

你不需要jQuery的,JS能做到這一點:

 
string.substr(start,length) 

start The index where to start the extraction. First character is at index 0 
length The number of characters to extract. If omitted, it extracts the rest of the string 
6

我還沒有檢查過這一個錯誤,所以你可能不得不調整糟糕的索引。

var txt = SomeStringFromFeed; 
if(txt.length > 10) 
{ 
    txt = txt.substr(0,10) + "..."; 
} 
return txt; 
11

您可以使用CSS來建立一個省略號:

.myparagraph { 
    white-space: nowrap; 
    width: 10em; 
    overflow: hidden; 
    text-overflow: ellipsis; 
} 

然後是不需要任何的jQuery或其他編碼。

參考文獻:

(注意,第一個鏈接 - Quirksmode.org是一般的CSS和Javascript的東西一個很好的資源)

+1

很酷的使用CSS。不知道文本溢出,我不得不更多地瞭解它。 – 2010-11-08 17:25:11

+0

CSS省略號很酷,但它只支持一行文本 – JoenasE 2014-04-28 10:40:01

2

我不相信@spudley提到的CSS解決方案是跨瀏覽器(沒有Firefox支持)。假設你當然在意這一點。他提供的第一個鏈接甚至指出了頁面右上角的有限支持。

現在,說了我有一個很好的小函數可能會過度需要你的東西,但我發現我經常在類似的情況下使用它。下面的代碼已經被評論過了,但是它只是在最後一個完整的單詞後面插入一個省略號。

所以,你可以返回「狗跳...」,而不是「狗跳奧雅納......」

// ============================================================================================== 
// Truncate a string to the given length, breaking at word boundaries and adding an elipsis 
//  @param str - String to be truncated 
//  @param limit - integer Max length of the string 
//  @returns a string 
// ============================================================================================== 

    function truncate(str, limit) { 
     var chars; 
     var i; 

     // check if what was passed as a string is actually a string 
     if (typeof(str) != 'string') { 
      return ''; 
     } 

     // create an array of the chars in the string 
     chars = str.split(''); 

     // if the length is greater than the set limit, process for truncating 
     if (chars.length > limit) { 
      // while the char count is greater than the limit, 
      for (i = chars.length - 1; i > -1; --i) { 
       // if char count is still greater, redefine the array size to the value of i 
       if (i > limit) { 
        chars.length = i; 
       } 
       // if char count is less than the limit keep going until you hit a space 
       // and redefine the array size to the value of i 
       else if (' ' === chars[i]) { 
        chars.length = i; 
        break; 
       } 
      } 
      // add elipsis to the end of the array 
      chars.push('...'); 
     } 
     // return the array as a string 
     return chars.join(''); 
    } 
+0

你當然是對的,它不支持Firefox * yet *(很快有希望?)。但所有其他瀏覽器都支持它(甚至IE早於IE5.5),所以它的覆蓋範圍很好,甚至Firefox也能正確截斷它。另外,還有一些瑣碎的解決方法可以讓它在使用XUL的Firefox中工作......但這是另外一個問題和答案。 – Spudley 2010-11-09 09:01:03

+0

@Spudley這是一個不錯的解決方案。我個人非常期待這個功能跨瀏覽器。我只是想確保他/她(以及其他任何可能在這個問題上偶然發現的答案)意識到,如果他們的需求需要跨瀏覽器解決方案,那麼他們可能不會像他們希望的那樣工作。 – 2010-11-09 13:52:08

+0

很酷。我會盡量使用這個 – JoenasE 2014-04-28 10:41:53