jquery
  • chaining
  • 2013-10-18 45 views 0 likes 
    0

    我正在使用jQuery獲取鏈接的內容,並希望用它的內容替換鏈接。jQuery鏈接獲取html和replaceWith

    我得到它的工作,但我想知道如果我可以寫在一個聲明而不是兩個。

    這裏是我的代碼:

    text = $(this).closest('.ui-btn-text').find("a[data-rel='popup']").html(); 
    $(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(text); 
    

    謝謝!

    回答

    2

    .replaceWith()函數接受返回新的HTML來替換該元素的功能,所以你可以這樣做:

    $(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(function() { 
        return $(this).html(); 
    }); 
    

    重要的是要注意, this裏面的函數傳遞給.replaceWith()不同於this在行首;在函數內部,它指的是當前匹配的元素被新的HTML取代。

    +0

    +1。這**一行**是OP正在尋找的答案。 – Bucket

    +0

    完美!這正是我正在尋找的。也謝謝你的解釋! – Sebsemillia

    1

    您可以優化它像

    textObj = $(this).closest('.ui-btn-text').find("a[data-rel='popup']"); 
    textObj.replaceWith(textObj.html()); 
    
    +0

    文本是未定義 – dezman

    +0

    對不起錯字,應該是textObj – Adil

    +2

    雖然這是正確的,OP是尋找如何做到這一點的一個聲明,而不是兩個。 – Bucket

    0
    var node = $(this).closest('.ui-btn-text').find("a[data-rel='popup']"); 
    node.replaceWith(node.html()); 
    
    相關問題