jQuery: How to go through all the characters in <p> paragraph?

醉酒当歌 提交于 2019-12-13 07:08:24

问题


I've got a 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>

How to realize it in jQuery?


回答1:


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

EDIT: If you wanted to assign different classes, you could do something like this:

Example: 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; }​



回答2:


Some combination of String.split() and jQuery.wrap() will probably do the trick.

Something like this: (untested, just whipped this up quickly)

var paragraph = $('<p>I want to put a ding in the universe.</p>');
var text = paragraph.text();
var newText = '';
$.each(text.split(), function(i, val) {
    if (val != ' ') {
        newText = newText + $(val).wrap('<span class="color"></span>');
    } else {
        newText = newText + val;
    }
});
paragraph.html(newText);



回答3:


A little slow with response but I have a working example: http://jsfiddle.net/YgzhK/

$(document).ready(
    function()
    {
        var oldText = $("#text").text(); 
        $("#text").html("");

        for (var i = 0; i < oldText.length; i++)
        {
            if (oldText.charAt(i) != " ")
                $("#text").append("<span class='color'>" + oldText.charAt(i) +"</span>");
            else
                $("#text").append(" ");
        }
    });​



回答4:


Since characters are not DOM-elements you need to build a new DOM:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <title>CharLoop</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
      <script type="text/javascript">
    $(document).ready(function() {
        $("p").each(function() {
            var $resultDom = $("<p/>");
            var $p = $(this);
            var text = $p.text();
            // Loop through every character in paragraph text
            for (var i=0, l = text.length; i < l; i++) {
                var $char = $("<span>" + text.charAt(i) + "</span>");
                // Set class
                $char.attr("class", "color" + i);
                // Set inline style if you don't want to hardcode alot of colors
                $char.css("color", "rgb(" + (i * 10) % 255 + "," + (i * 20) % 255 + "," + (i * 30) % 255 + ")");
                $resultDom.append($char);
            }
            $p.empty();
            $p.append($resultDom.children());
        });
    });
      </script>
   </head>
   <body>
      <p>I want to put a ding in the universe.</p>
      <p>Lorem ipsum</p>
   </body>
</html>

Beware of that this method might not be fast, and you are emptying the paragraph (<p />) so every information that is not text will be removed, for example links (<a />) will not be preserved. Result:



来源:https://stackoverflow.com/questions/3867594/jquery-how-to-go-through-all-the-characters-in-p-paragraph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!