2016-08-22 270 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(),但这会跳过一些图像,所以我更喜欢使用它。

相关问题