亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用jQuery將一個標簽替換為另一個標簽

使用jQuery將一個標簽替換為另一個標簽

湖上湖 2019-10-26 13:02:47
目標:使用jQuery,我試圖替換所有出現的情況:<code> ... </code>與:<pre> ... </pre>我的解決方案:我了解到以下內容:$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );我的解決方案的問題:但是問題在于它用第一個 “ code”標簽之間的內容替換了(第二,第三,第四等)“ code”標簽之間的所有內容。例如<code> A </code><code> B </code><code> C </code>變成<pre> A </pre><pre> A </pre><pre> A </pre>我想我需要使用“ this”和某種功能,但是恐怕我還在學習,并且不太了解如何將解決方案組合在一起。
查看完整描述

3 回答

?
Cats萌萌

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());

});


查看完整回答
反對 回復 2019-10-26
?
慕村225694

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.

});


查看完整回答
反對 回復 2019-10-26
?
30秒到達戰場

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');


查看完整回答
反對 回復 2019-10-26
  • 3 回答
  • 0 關注
  • 3841 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號