2012-03-28 81 views
1

我有這樣的事情:裹鏈接到的所有圖像一個div內使用jQuery

<img class="photo" src="www.example.com" /> 
<img class="photo" src="www.example2.com" /> 
<img class="photo" src="www.example3.com" /> 

,我需要得到這樣的:

<a href="www.example.com" class="link"> 
    <img class="photo" src="www.example.com" /> 
</a> 
<a href="www.example2.com" class="link"> 
    <img class="photo" src="www.example.com2" /> 
</a> 
<a href="www.example3.com" class="link"> 
    <img class="photo" src="www.example.com3" /> 
</a> 

我需要添加鏈接,將href與每個圖像的SRC相同的代碼和一個類。

我試圖做這樣的:

$('.photo').wrapAll('<a>'); 

但它甚至不工作。 我在做什麼錯?

謝謝。

+0

'$ wrapAll( '');' ? Or '$('.photo').wrapAll('(」照片')。 「);'? http://api.jquery.com/wrapAll/ – PeeHaa 2012-03-28 15:43:19

+0

它不起作用。圖像與jquery加載與:d_row.append(img); – Alvaro 2012-03-28 16:53:05

回答

8

因爲hrefs將全部不同,所以您需要使用each

$('img.photo').each(function() { 
    var $img = $(this), 
     href = $img.attr('src'); 
    $img.wrap('<a href="' + href + '" class="link"></a>'); 
}); 

注意wrapAll是不是你想要的呢,因爲它需要的所有元素,並用一個錨標記包裝他們。如果您沒有使用每個元素都需要不同href的錨,則wrap可以獨立工作並分別包裝每個元素。

+0

聽起來很不錯,但它似乎不適合我的代碼。 這可能是因爲圖像未加載到網站上,它們是通過javascript逐一添加的:d_row.append(img); 有什麼幫助嗎?謝謝。 – Alvaro 2012-03-28 16:52:27

+0

如果要動態添加它,可以在追加它之前將它包裝起來,或者在將它添加到DOM之前簡單地構建要追加的HTML以包含鏈接。 – tvanfosson 2012-03-28 17:08:01

+0

我已經用這段代碼和其餘的答覆嘗試過了,沒有人對圖像做任何事情。它沒有添加任何東西。 – Alvaro 2012-03-28 17:13:23

1

$('img').wrap("<a href='foo'>")將工作得很好。

0

試試這個:

$('.photo').before('<a href="www.example3.com" class="link">'); 
$('.photo').after('</a>'); 

如果你想

$('.photo').each(function() { 
    var mySrc = $(this).attr("src"); 
    $(this).before('<a href="' + mySrc + '" class="link">')); 
    $(this).after('</a>')); 
}); 

我希望這對你的作品...

+0

我的圖像在d_row.append(img)之後用JavaScript加載; 所以這不起作用。 – Alvaro 2012-03-28 16:53:26

相關問題