2012-10-15 29 views
1

我得到這個HTML代碼:獲取父DIV ID,並適用於元素

<div class="gallery" id="gallery_x"> 
    <p> 
     <a href="http://a-dynamic-link.com">image1</a> 
     <a href="http://another-dynamic-link-com">image2</a> 
    </p> 
</div> 

(X =變量個數)

,我需要從DIV名爲.gallery得到ID,並將其應用到「一」 作爲一個相對就像這樣:

<div class="gallery" id="gallery_x"> 
    <p> 
     <a rel="gallery_x" href="http://a-dynamic-link.com">image1</a> 
     <a rel="gallery_x" href="http://another-dynamic-link-com">image2</a> 
    </p> 
</div> 

我(不工作)解決方案迄今:

$(".gallery a").parents(".gallery").attr("rel", $(this).attr("id")); 

如果有人能幫助我,我會很高興。

謝謝。

回答

3
$(".gallery").each(function(){ 
    $("a", this).attr("rel", $(this).attr("id")); 
}); 
+0

這正是我需要的,謝謝! – dee

2

試試這個:

$('.gallery a').attr('rel', function() { 
    return $(this).closest('div').attr('id'); 
});​ 
+0

沒有'的問題this'背景 – billyonecan

+0

@billyonecan謝謝,你是對的..更新我的回答 –

+0

NP,它是幾分鐘後,我意識到自己:p – billyonecan