jQuery:如何浏览< p>中的所有字符;段落? [英] jQuery: How to go through all the characters in <p> paragraph?
问题描述
我有一个段落:<p>I want to put a ding in the universe.</p>
我想更改文本中字符的属性,例如更改其颜色,因此在此之后,该段应如下所示:
I want to change the attributes of the characters in the text e.g. to change its color, so after this the paragraph should look like this:
<p>
<span class="color">
I
</span> <span class="color">
w
</span><span class="color">
a
</span><span class="color">
n
</span><span class="color">
t
</span>...
</p>
<p>
<span class="color">
I
</span> <span class="color">
w
</span><span class="color">
a
</span><span class="color">
n
</span><span class="color">
t
</span>...
</p>
如何在jQuery中实现它?
How to realize it in jQuery?
推荐答案
我看不到用具有相同类的跨度单独包装的意义,但是在这里,您去了:
I don't see the point of wrapping individually with the spans that have the same class, but here you go:
var $p = $('p');
var array = $p.text().split('');
var result = '<span class="color">' +
array.join('</span><span class="color">') +
'</span>';
$p.html(result);
编辑:如果您想分配其他类别,则可以执行以下操作:
If you wanted to assign different classes, you could do something like this:
示例: http://jsfiddle.net/LnD6W/1/
var $p = $('p');
var array = $p.text().split('');
var colors = ['green','blue','orange','yellow','red'];
$.each(array, function( i ) {
array[i] = '<span class="' + colors[ i % 5 ] + '">' + array[i] + '</span>';
});
$p.html(array.join(''));
CSS
.green { color:green; }
.blue { color: blue; }
.orange { color: orange; }
.yellow { color: yellow; }
.red { color: red; }
这篇关于jQuery:如何浏览< p>中的所有字符;段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!