2011-10-25 117 views
1

后,添加图片,这是对everypost如何超级链接

<div class="post-body"> 
<a href="http://www.google.com">google</a> 
<a href="http://www.youtube.com">youtube</a> 
<a href="http://www.facebook.com">facebook</a> 
</div> 

每个链接,如<a href="http://www.google.com">google</a>的HTML具有相同的超链接在这种情况下<a href="http://www.google.com">google</a>添加图像和图片src 内http://open.thumbshots.org/image.aspx?url=后添加超链接所以结果将是<img src="http://open.thumbshots.org/image.aspx?url=http://www.google.com" width="120px" />

下面的代码是每个帖子中html的结果。

<div class="post-body"> 
    <a href="http://www.google.com">google</a> 
    <a href="http://www.google.com"><img src="http://open.thumbshots.org/image.aspx?url=http://www.google.com" width="120px" /></a> 


    <a href="http://www.youtube.com">youtube</a> 
    <a href="http://www.youtube.com"><img src="http://open.thumbshots.org/image.aspx?url=http://www.youtube.com" width="120px" /></a> 


    <a href="http://www.facebook.com">facebook</a> 
    <a href="http://www.facebook.com"><img src="http://open.thumbshots.org/image.aspx?url=http://www.facebook.com" width="120px" /></a> 
    </div> 

回答

3

这是比较简单的:

$('.post-body a').each(
    function(){ 
     $('<img />').attr('src','http://open.thumbshots.org/image.aspx?url='+ this.href).insertAfter($(this)); 
    }); 

JS Fiddle demo

虽然它可能是明智通过encodeURIComponent()运行网站网址,只是为了安全起见:

$('.post-body a').each(
    function(){ 
     $('<img />').attr('src','http://open.thumbshots.org/image.aspx?url='+encodeURIComponent(this.href)).insertAfter($(this)); 
    }); 

JS Fiddle demo。另外,只是为了演示,如果不彻底,这并不需要jQuery;同样可以通过使用普通的JavaScript(虽然在一个相当少简洁的方式)来实现:

var container = document.getElementsByClassName('post-body')[0]; 
var links = container.getElementsByTagName('a'); 
var imgSrc = 'http://open.thumbshots.org/image.aspx?url='; 

for (i = 0; i < links.length; i++) { 
    var img = document.createElement('img'); 
    var linkURL = encodeURIComponent(links[i].href); 
    img.src = imgSrc + linkURL; 
    container.insertBefore(img,links[i].nextSibling); 
} 

JS Fiddle demo

关于Floyd Pink的评论,我必须承认我错过了将图片作为链接的需求。以下是服用该保健有点混乱的方式,但我觉得必须有一个整洁的远路:

$('.post-body a').each(

function() { 
    $('<img />').attr('src', 'http://open.thumbshots.org/image.aspx?url=' + encodeURIComponent(this.href)).insertAfter($(this)).parent().find('img:last').wrap('<a></a>').closest('a').attr('href',this.href); 
}); 

JS Fiddle demo

+0

OP要求是超链接本身... –

2

我倾向于更喜欢this approach,但@David也有很好的答案。

$('a').each(function(){ 
    $(this).clone() 
    .empty() 
    .append(
     $('<img>',{ 
      width:120, 
      src:'http://open.thumbshots.org/image.aspx?url='+encodeURIComponent(this.href) 
     }) 
    ) 
    .insertAfter(this); 
}); 
+1

并注意图像:我只克隆原来的锚(然后清空),以保持匹配的锚(针对原始链接和新的图像) –

+0

+1对于这样做的更直接的方式,无需在DOM树上下...感叹。当我累了时,我可能不应该发布代码... –