2012-04-02 4 views
0

Ich möchte die String-Länge aller meine $ ("a.paragraph") begrenzen. Ich habe den folgenden Code:Wie kann die String-Länge mehrerer Elemente mit jquery begrenzt werden?

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); 
} 

Dieser Code reworks das erste Element nur und zeigt das Ergebnis auf allen Absätzen. Wie kann ich jeden einzelnen Absatz wiederholen?

Antwort

4

Sie können von jQuery's each function machen:

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

danke, das war genau das, was ich gesucht habe. Ich habe jeden versucht, aber vergessen, 'dieses' zu verwenden. –

2

Mit .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

Sie müssen jeden Absatz und Schleife um sie zu finden:

$("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

Sie benötigen Schleife über jedes Element. Das Verhalten, das Sie feststellen, ist die Art, wie jQuery standardmäßig funktioniert.

$("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); 
    } 
}); 
Verwandte Themen