2011-10-25 116 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樹上下...感嘆。當我累了時,我可能不應該發佈代碼... –