使用jQuery:如何将每个字母包装在标签中?

Rob*_*Rob 5 jquery

我花了两天时间,所以如果有一个简单的答案,我会感到沮丧.我试图在div中的每个字母周围放置一个span标记,同时保留其余的标记.

<div id="div">
    <p>
      Of course some of the <strong>text is in other tags</strong> and <strong>some 
      is  in <em>nested tags</em>, etc.</strong>
    </p>
</div>
Run Code Online (Sandbox Code Playgroud)

我非常接近,但总有一些事情让我兴奋不已.

Tes*_*rex 2

我得到了它!这可能不是最佳解决方案,但它确实有效!另请注意,由于存在额外的标签,空格可能会变得混乱。这也会包裹标签,但这也很容易修复。

function wrap(target) {
    var newtarget = $("<div></div>");
    nodes = target.contents().clone(); // the clone is critical!
    nodes.each(function() {
        if (this.nodeType == 3) { // text
            var newhtml = "";
            var text = this.wholeText; // maybe "textContent" is better?
            for (var i=0; i < text.length; i++) {
                if (text[i] == ' ') newhtml += " ";
                else newhtml += "<span>" + text[i] + "</span>";
            }
            newtarget.append($(newhtml));
        }
        else { // recursion FTW!
            $(this).html(wrap($(this)));
            newtarget.append($(this));
        }
    });
    return newtarget.html();
}
Run Code Online (Sandbox Code Playgroud)

用法:

$("#div").html(wrap($("#div")));
Run Code Online (Sandbox Code Playgroud)