3 回答

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

TA贡献1880条经验 获得超4个赞
正确的是,您始终将获得first 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.
});

TA贡献1828条经验 获得超6个赞
建立在Felix的答案上。
$('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;
});
这将code在替换pre标签中复制标签的属性。
编辑:这将取代甚至code是里面的标签innerHTML等的code标签。
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');
添加回答
举报