我明白了!这可能不是最佳的解决方案,但它的工作原理!还要注意,由于额外的标签,空白可能会混乱。这也包装标签,但也很容易解决。
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();
}
用法:
$("#div").html(wrap($("#div")));
符合儿童的标签也应该得到周围标签的字母? – 2010-06-04 20:15:38
你为什么想这样做? – aviraldg 2010-06-04 20:16:08
这是不知道嵌套标记,但可能会给一些groudnwork:http://stackoverflow.com/questions/1966476/javascript-process-each-letter-of-text – 2010-06-04 20:16:35