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');
添加回答
舉報