2012-06-19 57 views
1

我有HTML這樣的:jQuery的:讓孩子屬性

<div> 
    <a href="">sometext<img src="images/001.jpg" /></a> 
    <a href="">sometext<img src="images/002.jpg" /></a> 
    ... 
    <a href="">sometext<img src="images/nnn.jpg" /></a> 
</div> 

我要的是讓 'HREF' atrributes等於使用jQuery孩子 'IMG' 的 'SRC' 屬性。這是我的失敗嘗試(沒有JS錯誤,但沒有結果):

$('div a').attr('href', $(this).children('img').attr('src')); 

我怎樣才能得到孩子「IMG」的「SRC」屬性像父「A」 ATTR()第二個參數的使用?

回答

4
$('div a').attr('href', function() { 
    return $(this).find('img').attr('src'); 
}); 

DEMO

+0

+1比我的'each'嘗試好得多:-) – ManseUK

+0

@ManseUK謝謝Sir – thecodeparadox

+0

@thecodeparadox謝謝。 如果我知道img總是隻有一個級別的後代,我可以使用'children()'方法(它是更好還是更快?)。 – McSimKammerer

1

試試這個:

$('div a').each(function(){ 
    $(this).attr('href', $(this).find('img').attr('src')); 
}) 
0

你可以循環每個img和設置父href屬性是這樣的:

$('div a img').each(function() { 
    $(this).parent().attr('href',$(this).attr('src')); 
}); 

Working example here