目标:
使用 jQuery,我试图替换所有出现的:
<code> ... </code>
与:
<pre> ... </pre>
我的解决方案:
我得到了以下,
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );
我的解决方案的问题:
但问题是它用第一个“代码”标签之间的内容替换了(第二个、第三个、第四个等)“代码”标签之间的所有内容。
例如
<code> A </code>
<code> B </code>
<code> C </code>
成为
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>
我认为我需要使用“this”和某种功能,但恐怕我仍在学习并且并不真正理解如何将解决方案组合在一起。
最佳答案
您可以将函数传递给 .replaceWith
[docs] :
$('code').replaceWith(function(){
return $("<pre />", {html: $(this).html()});
});
在函数内部,this
指的是当前处理的code
元素。
更新:有no big performance difference , 但如果 code
元素有其他 HTML 子元素,附加子元素而不是序列化它们感觉更正确:
$('code').replaceWith(function(){
return $("<pre />").append($(this).contents());
});
关于javascript - 使用 jQuery 将一个标签替换为另一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7093417/