用jQuery包装每个字符除了标签 [英] wrap each char in except tags with jQuery
问题描述
我试图将每个文本字符包装在
< div id =test>< / DIV>
带有span标签。
这里没问题,只是我还需要保持嵌套标签不被修改。
所以如果DIV中的字符串是:
有些随机文字,< b>但< / b>等 - 有< a href =http://w3.org> ;标签< / a>里面!
它应该为but部分输出这个部分
< b>< span> b< / b>< span> u< / span>< span> t< / span>< / b>
离开< b>和< a>标签,但是包含所有其他字符。我检查了文本(),但似乎没有保存标签或保存的方法,只提取文本并永久删除< b>和< a>
也许有些jQuery专家知道如何做到这一点?
$(div)。children()。andSelf ().contents()。each(function(){
if(this.nodeType == 3){
var $ this = $(this);
$ this.replaceWith($ this.text()。replace(/(\w)/ g,< span> $&< / span>));
}
});
请参阅测试在jsFiddle案件。
I'm trying to wrap each text character inside a
<div id="test"></div>
with a span tag. No problem there, it's just that I also need to keep nested tags unmodified.
So if the string inside the DIV is:
"Some random text, <b>but</b> wait - there's <a href="http://w3.org">tags</a> inside!"
It should output this for the "but" part
<b><span>b</b><span>u</span><span>t</span></b>
Leaving the < b> and < a> tags alone, but wrapping all other chars in span. I checked text() but that doesn't seem to have a way of preserving tags or "saving back", only extracting the text and permanently removing the < b> and < a>
Maybe some jQuery guru out there knows how to do this?
You can do this by using the following code:
$("div").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
}
});
这篇关于用jQuery包装每个字符除了标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!