2012-04-02 95 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); 
    } 
});