如何防止replaceWith生成多个文本节点?
我有这段 html 代码:
<p><span>h</span><span>o</span><span>l</span><span>a</span></p>
我在上面使用 jQuery 来替换所有的跨度:
$('p span').each(function(){
$(this).replaceWith($(this).text());
});
当我查看 DOM 时,我看到脚本创建了 4 个文本节点,每个字母一个。 如何防止这种情况发生?我只想要 1 文本节点!
注意:给出的示例非常简单。 我实际上是这样做的:
<p>This is an <b>example</b>: <span>h</span><span>o</span><span>l</span><span>a</span>!</p>
这应该看起来像:
<p>{text}This is an {/text}<b>{text}example{/text}</b>{text}: hola!{/text}</p>
{text} 是一个 DOM 文本节点:-)
I have this piece of html code:
<p><span>h</span><span>o</span><span>l</span><span>a</span></p>
And I'm using the jQuery on it to replace all the spans:
$('p span').each(function(){
$(this).replaceWith($(this).text());
});
When I look into my DOM I see the script created 4 text nodes, for each letter one. How can I prevent this from happening? I only want 1 text node!
Note: the given example is very very simplified.
I'm actually doing it on:
<p>This is an <b>example</b>: <span>h</span><span>o</span><span>l</span><span>a</span>!</p>
That should look like:
<p>{text}This is an {/text}<b>{text}example{/text}</b>{text}: hola!{/text}</p>
{text} is a DOM-text node :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许你真的想要这个?
实际操作: http://jsfiddle.net/2qNGY/
Perhaps you really want this?
In action: http://jsfiddle.net/2qNGY/
您可以做的一件事是最后调用本机
normalize()
方法:
编辑: 我以前使用过
parent( )
(docs) 从元素向上遍历,但它们已从DOM,所以他们不再有父母。
现在,我首先选择
,然后选择
find()< /code>(docs)
元素。这样我就可以使用
end()
(docs) 返回到,并调用
.normalize()
。如果有多个
元素,您将需要执行另一个循环。
您还可以将函数作为参数传递给
replaceWith()
(docs) 返回每个元素的文本。One thing you could do is at the end, call the native
normalize()
method:EDIT: I was previously using
parent()
(docs) to traverse up from the<span>
elements, but they were removed from the DOM, so they no longer had a parent.Instead now I first select the
<p>
, thenfind()
(docs) the<span>
elements. This way I can useend()
(docs) to get back to the<p>
, and call.normalize()
.If there are several
<p>
elements, you'll want to do another loop.You could also pass a function as a parameter to
replaceWith()
(docs) which returns the text of each element.