3

我有这段 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 文本节点 :-)

4

2 回答 2

2

您可以做的一件事是最后调用本机normalize()方法:

$('p').find('span').each(function(){
   $(this).replaceWith($(this).text());     
}).end()[0].normalize();

编辑:我以前使用parent()(docs) 从元素向上遍历<span>,但它们已从 DOM 中删除,因此它们不再有父元素。

相反,现在我先选择<p>,然后选择find()(docs)<span>元素。这样我可以使用end()(docs)回到<p>, 并调用.normalize().

如果有多个<p>元素,您将需要执行另一个循环。

$('p').find('span').each(function(){
   $(this).replaceWith($(this).text());     
}).end().each(function() {
    this.normalize();
});

您还可以将函数作为参数传递给replaceWith()(docs),它返回每个元素的文本。

$('p').find('span').replaceWith(function(i,el){ 
    return $.text([this]);
}).end().each(function() {
    this.normalize();
});
于 2011-01-21T14:25:08.753 回答
1

也许你真的想要这个?

$('p').text(function (i, txt) {
    return txt;
});

在行动:http: //jsfiddle.net/2qNGY/

于 2011-01-21T14:24:46.347 回答