2016-08-22 40 views
0

我試圖想出可以取代文本鏈接的功能。標籤內的圖像應該移動到包裝上,原始的a應該被移除。如何使用JQuery將鏈接轉換爲文本?

JS:

var selectors = 'a.mark-video;a.sp5;a>img[alt!=""]' 
selectors = selectors.split(";").join(", "); 

$(selectors).each(function() { 
    var current = this; 
    if (this.nodeName == "IMG") { 
     current = this.parentNode; 
     if (current.nodeName != "A") 
     current = this.parentNode; 
     if (current.nodeName != "A") 
     return false; 
     current = $(current); 
    } 
    var wrapper = current.parent(); 
    var new_context = $().append(current.html()); 
    current.remove(); 
    wrapper.append(new_context); 
    } 
); 

問題是 1),該圖像沒有被插入到所述包裝 2)如果將它插入它不會有正確的位置。

我使用webextensions API(火狐插件),我嘗試注入代碼到網站: http://zpravy.idnes.cz/zahranicni.aspx

在調試器中,你可以看到兩個包裝帶class =「藝術」。我刪除了第一個鏈接,但未插入圖像。當第一次迭代後調試器暫停時,第二個還沒有被刪除。

enter image description here

我希望你能找出爲什麼圖像不追加,以及如何將其追加到元素a的原始位置。我需要首先找到元素a的位置,然後將圖像移動到正確的位置 - 即在div.art-info之前。

注:請不要改變選擇的字符串。這是來自表單字段的用戶輸入。

編輯:

幾乎有:

function(){ 
    if (this.parentNode.nodeName == "A") 
    $(this.parentNode).replaceWith($(this)); 
    else 
    $(this).html().replaceWith($(this)); // error: html() result does not have replaceWith... 
    } 
+0

在突出顯示的代碼中,目標是採用該錨標記中的鏈接並使用'' – Novocaine

+0

編號將其變爲圖像。圖像必須保持不變/不變。它應該使圖像不可點擊。所以你可以點擊任何圖像而不被重定向。 – user1141649

回答

1

這是你在找什麼?

https://jsfiddle.net/4tmz92to/

var images = $('a > img'); 

$.each(images, function(key, image) { 
    $(this).parent().replaceWith(image); 
}); 

首先選擇所有你想通過他們移除,然後循環鏈接,只需更換parent()與圖像的圖像。

+0

基本上,但我可以改變我的功能使用replaceWith()。它將刪除鏈接並插入圖像。好主意。謝謝。 – user1141649

+0

如果我搜索$(「a」)。html()並且想要將鏈接「a」替換爲innertext,您將如何解決它? html()結果沒有replaceWith。 – user1141649

+1

而不是'$(this).html()。replaceWith()'它只是'$(this).replaceWith()'。你不需要'.html()'*和*'.replaceWith()' – Novocaine

0

我終於解決了這個問題:

$(selectors).each(
function(){ 
    if (this.parentNode.nodeName == "A") 
    $(this.parentNode).replaceWith($(this)); 
    else 
    $(this).replaceWith(
     $(this).html() 
    ); 
    } 
); 

的使用方法類似。 Novocaine建議不要使用$(this).html(),但這會跳過一些圖像,所以我更喜歡使用它。

相關問題