2012-04-02 111 views
0

我想限制所有$(「a.paragraph」)的字符串長度。我有以下代碼:如何用jquery限制多個元素的字符串長度?

var paragraph = $("a.paragraph").text(); 
var maxlength = 500; 
var strlength = paragraph.length; 
if (strlength > maxlength) { 
    var introduction = paragraph.substr(0,maxlength); // cut string 
    var search   = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut) 
    introduction  = introduction.substr(0, search); // cut string until last space 
    introduction  = introduction + "..."; // add ... in the end 
    $("a.paragraph").text(introduction); 
} 

此代碼僅返工的第一個元素,並顯示所有段落的結果。我怎樣才能循環每一段?

回答

4

您可以使用jQuery's each function

$('a.paragraph').each(function() { 
    var paragraph = $(this).text(); 
    // ... do stuff here 
}) 
+0

謝謝你,這正是我所尋找的。我嘗試了每個,但忘了使用'這個'。 – 2012-04-02 18:58:32

2

使用.each

$('a.paragraph').each(function() { 
    var paragraph = $(this).text(); 
    var strlength = paragraph.length; 
    if (strlength > maxlength) { 
     var introduction = paragraph.substr(0, maxlength); // cut string 
     var search   = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut) 
     introduction  = introduction.substr(0, search); // cut string until last space 
     introduction  = introduction + "..."; // add ... in the end 
     $(this).text(introduction); 
    } 
}); 
1

你需要找到他們周圍的每個段落和循環:

$("a.paragraph").each(function() { 
    var paragraph = $(this).text(); 
    var maxlength = 500; 
    var strlength = paragraph.length; 
    if (strlength > maxlength) { 
     var introduction = paragraph.substr(0,maxlength); // cut string 
     var search   = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut) 
     introduction  = introduction.substr(0, search); // cut string until last space 
     introduction  = introduction + "..."; // add ... in the end 
     $("a.paragraph").text(introduction); 
    } 
}); 
1

您需要循環在每個元素上。您遇到的行爲是jQuery默認工作的方式。

$("a.paragraph").each(function(i,e) { 
    var paragraph = $(e).text(); 
    var maxlength = 500; 
    var strlength = paragraph.length; 
    if (strlength > maxlength) { 
     var introduction = paragraph.substr(0,maxlength); // cut string 
     var search   = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut) 
     introduction  = introduction.substr(0, search); // cut string until last space 
     introduction  = introduction + "..."; // add ... in the end 
     $(e).text(introduction); 
    } 
});