jon*_*jon 98 javascript jquery replace
使用jQuery,我试图替换所有出现的:
<code> ... </code>
Run Code Online (Sandbox Code Playgroud)
有:
<pre> ... </pre>
Run Code Online (Sandbox Code Playgroud)
我得到了以下,
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );
Run Code Online (Sandbox Code Playgroud)
但问题是,它正在用第一个 "代码"标签之间的内容替换(第二,第三,第四等)"代码"标签之间的所有内容.
例如
<code> A </code>
<code> B </code>
<code> C </code>
Run Code Online (Sandbox Code Playgroud)
变
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>
Run Code Online (Sandbox Code Playgroud)
我想我需要使用"这个"和某种功能,但我担心我还在学习,并且不太懂得如何将解决方案拼凑在一起.
Fel*_*ing 153
您可以将函数传递给.replaceWith [docs]:
$('code').replaceWith(function(){
return $("<pre />", {html: $(this).html()});
});
Run Code Online (Sandbox Code Playgroud)
函数内部this是指当前处理的code元素.
更新:有没有什么大的性能差异,但万一code元素具有其他HTML孩子,追加的孩子而序列化他们感觉是更正确的:
$('code').replaceWith(function(){
return $("<pre />").append($(this).contents());
});
Run Code Online (Sandbox Code Playgroud)
Jen*_*and 80
这更好:
$('code').contents().unwrap().wrap('<pre/>');
Run Code Online (Sandbox Code Playgroud)
虽然Felix Kling的解决方案速度大约是其两倍:
pim*_*vdb 26
你总是会获得第一个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.
});
Run Code Online (Sandbox Code Playgroud)
Kok*_*kos 12
试试这个:
$('code').each(function(){
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});
Run Code Online (Sandbox Code Playgroud)
Tae*_*hin 11
这个怎么样?
$('code').each(function () {
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});
Run Code Online (Sandbox Code Playgroud)
建立菲利克斯的答案.
$('code').replaceWith(function() {
var replacement = $('<pre>').html($(this).html());
for (var i = 0; i < this.attributes.length; i++) {
replacement.attr(this.attributes[i].name, this.attributes[i].value);
}
return replacement;
});
Run Code Online (Sandbox Code Playgroud)
这将重现code替换pre标签中标签的属性.
编辑:这将替换其他标记code内的标记.innerHTMLcode
function replace(thisWith, that) {
$(thisWith).replaceWith(function() {
var replacement = $('<' + that + '>').html($(this).html());
for (var i = 0; i < this.attributes.length; i++) {
replacement.attr(this.attributes[i].name, this.attributes[i].value);
}
return replacement;
});
if ($(thisWith).length>0) {
replace(thisWith, that);
}
}
replace('code','pre');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63930 次 |
| 最近记录: |