使用jQuery将一个标签替换为另一个标签

目标:

使用jQuery,我试图替换所有出现的情况:


<code> ... </code>

与:


<pre> ... </pre>

我的解决方案:

我了解到以下内容:


$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );

我的解决方案的问题:

但是问题在于它用第一个 “ code”标签之间的内容替换了(第二,第三,第四等)“ code”标签之间的所有内容。


例如


<code> A </code>

<code> B </code>

<code> C </code>

变成


<pre> A </pre>

<pre> A </pre>

<pre> A </pre>

我想我需要使用“ this”和某种功能,但是恐怕我还在学习,并且不太了解如何将解决方案组合在一起。


湖上湖
浏览 3701回答 3
3回答

Cats萌萌

您可以将一个函数传递给.replaceWith [docs]:$('code').replaceWith(function(){&nbsp; &nbsp; return $("<pre />", {html: $(this).html()});});在函数内部,this引用当前处理的code元素。演示更新:并没有很大的性能差异,但是如果code元素具有其他HTML子元素,则附加子元素而不是对其进行序列化会更正确:$('code').replaceWith(function(){&nbsp; &nbsp; return $("<pre />").append($(this).contents());});

慕村225694

正确的是,您始终将获得first code的内容,因为$('code').html()无论您在何处使用它都将始终引用第一个元素。相反,您可以.each用来遍历所有元素并分别更改每个元素:$('code').each(function() {&nbsp; &nbsp; $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );&nbsp; &nbsp; // this function is executed for all 'code' elements, and&nbsp; &nbsp; // 'this' refers to one element from the set of all 'code'&nbsp; &nbsp; // elements each time it is called.});

30秒到达战场

建立在Felix的答案上。$('code').replaceWith(function() {&nbsp; &nbsp; var replacement = $('<pre>').html($(this).html());&nbsp; &nbsp; for (var i = 0; i < this.attributes.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; replacement.attr(this.attributes[i].name, this.attributes[i].value);&nbsp; &nbsp; }&nbsp; &nbsp; return replacement;});这将code在替换pre标签中复制标签的属性。编辑:这将取代甚至code是里面的标签innerHTML等的code标签。function replace(thisWith, that) {&nbsp; &nbsp; $(thisWith).replaceWith(function() {&nbsp; &nbsp; &nbsp; &nbsp; var replacement = $('<' + that + '>').html($(this).html());&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < this.attributes.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; replacement.attr(this.attributes[i].name, this.attributes[i].value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return replacement;&nbsp; &nbsp; });&nbsp; &nbsp; if ($(thisWith).length>0) {&nbsp; &nbsp; &nbsp; &nbsp; replace(thisWith, that);&nbsp; &nbsp; }}replace('code','pre');
打开App,查看更多内容
随时随地看视频慕课网APP