add a class to and limit the ammount of html
I have a div id="X" within that i have multiple p , what i want is that jquery select the first p and from that p take the first 25 words and give them the Class excerpt
$("p:first").addClass("开发者_运维知识库excerpt");
This isn't a problem but how to limit the words ?
You have to go into the text node inside the p
element and split up the text data, then put a new wrapper element around those words, and give that wrapper a class. You can't add a class directly to text itself.
jQuery doesn't really give you much in the way of tools for manipulating text nodes so you will have to do this using some plain DOM too, eg:
var p= $('p')[0];
if (p.firstChild!==null && p.firstChild.nodeType===3) { // TEXT_NODE
// work out how many characters into the text 25 words is
var ix= p.firstChild.data.match(/^\s*(\S+\s*){0,25}/)[0].length;
// split into two text nodes
p.firstChild.splitText(ix);
// put the first of them into a span
$(p.firstChild).wrap('<span class="excerpt">');
}
This requires that the text in the element be a single direct text node. If you've got a situation where there are more elements inside the text, eg:
<p>
a b c d e f g h i j k l m n o
<em>p q r s t u v w x y (25th word here) z</em>
</p>
then the question becomes much trickier, as you can't wrap a <span>
around just part of an element.
you may also consider the work of Ben Nadel as described here:
http://www.bennadel.com/blog/1718-Ask-Ben-Displaying-A-Blog-Teaser-Showing-The-First-N-Words-.htm
then, based on his work, you can do something like this:
$(function() {
tag = $('p');
wordcount = 5;
partclass = 'strong';
var rawContent = $.trim( tag.text() );
rawContent = rawContent.replace(new RegExp( "\\s+", "g" )," ");
var snippets = rawContent.match(new RegExp( "([^\\s]+\\s?){1," + wordcount + "}", "g"));
if (!snippets.length){
snippets = [ "Nothing" ];
}
var wc = (
(wordcount * (snippets.length - 1)) +
snippets[ snippets.length - 1 ].split( " " ).length
);
tag.html(
"<span class=\""+partclass+"\">" +
snippets[ 0 ] + "</span>"
);
for (a = 1; a < snippets.length; a++)
tag.append(snippets[a]);
});
live example here
var p = $('#X p:first'),
t = p.text().split(/" "+/g),
n = 25,
txt = "",
span = function(word){
return "<span class='excerpt'>"+word+"</span>";
};
for(var i in t)
txt += i > n ? t[i]+" " : span(t[i]+" ");
p.text(txt);
What this function does is dividing the text in the first paragraph from the div with the id "X" into words.
Then, for the first n
(in this case 25) words, it wraps them into a span
element with the class "excerpt".
So, if your p looks like :
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
and you set the n
to 3,after altering it, you will have :
<p>
<span class='excerpt'>Lorem</span>
<span class='excerpt'>ipsum</span>
<span class='excerpt'>dolor</span>
sit amet, consectetur adipisicing elit
</p>
精彩评论