目标:
使用jQuery,我尝试替换所有出现的:
<code> ... </code>通过以下方式:
<pre> ... </pre>我的解决方案是:
我得到了如下结论:
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );我的解决方案的问题是:
但问题是,它用first“代码”标记之间的内容替换了(第二、第三、第四等)“代码”标记之间的所有内容。
例如:
<code> A </code>
<code> B </code>
<code> C </code>变成了
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>我想我需要使用"this“和一些函数,但我担心我还在学习,并不真正理解如何拼凑出一个解决方案。
发布于 2011-08-17 21:19:36
发布于 2011-08-17 21:14:05
您将始终获得第一个code的内容,这是正确的,因为$('code').html()将始终引用第一个元素,无论您在哪里使用它。
相反,您可以使用.each遍历所有元素并分别更改每个元素:
$('code').each(function() {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
    // this function is executed for all 'code' elements, and
    // 'this' refers to one element from the set of all 'code'
    // elements each time it is called.
});发布于 2011-08-17 21:14:56
试试这个:
$('code').each(function(){
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});http://jsfiddle.net/mTGhV/
https://stackoverflow.com/questions/7093417
复制相似问题