使用jQuery将一个标签替换为另一个标签 [英] Using jQuery to replace one tag with another
问题描述
使用jQuery,我正在尝试替换所有出现的事件:
Using jQuery, I'm trying to replace all the occurrences of:
<code> ... </code>
with:
<pre> ... </pre>
我的解决方案:
我得到了远至以下,
My solution:
I got as far as the following,
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );
我的解决方案存在问题:
但问题是,它正在替换(第二,第三,第四等)代码标签与第一个代码标签之间的内容之间的所有内容。
The problem with my solution:
but the issues is that it's replacing everything between the (second, third, fourth, etc)"code" tags with the content between the first "code" tags.
例如。
<code> A </code>
<code> B </code>
<code> C </code>
变为
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>
我想我需要使用这个和某种功能,但我害怕我我还在学习,并不真正理解如何将解决方案拼凑在一起。
I think I need to use "this" and some sort of function but I'm afraid I'm still learning and don't really understand how to piece a solution together.
推荐答案
您可以将功能传递给 .replaceWith
[docs] :
You can pass a function to .replaceWith
[docs]:
$('code').replaceWith(function(){
return $("<pre />", {html: $(this).html()});
});
在函数内部,此
指的是目前已处理代码
元素。
Inside the function, this
refers to the currently processed code
element.
更新:有没有大的性能差异,但是如果代码
元素有其他HTML子项,附加子项而不是序列化它们感觉更正确:
Update: There is no big performance difference, but in case the code
elements have other HTML children, appending the children instead of serializing them feels to be more correct:
$('code').replaceWith(function(){
return $("<pre />").append($(this).contents());
});
这篇关于使用jQuery将一个标签替换为另一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!