2014-07-04 135 views
1

我正在一個畫廊,我需要添加一個類的圖像時,覆蓋div徘徊。抓最接近的元素

這是我的HTML

<div class="overlayForCarDetails"></div> 
<a href="img/car_details/1large.jpg" rel="shadowbox"> 
    <img class="mediumImg" src="img/car_details/1medium.jpg" alt=""> 
</a> 

這是我的javascript

 $('.overlayForCarDetails').mouseenter(function() { 
      $(this).css('opacity', '0.7'); 
      $(this).closest('.mediumImg').addClass('zoomed'); 

     }); 

但不知何故,它不工作。 你能告訴我我在哪裏做錯了嗎? 謝謝。

回答

3

你必須使用.next().find()代替.closest()(如最近的擡頭層次),如下圖所示:

$('.overlayForCarDetails').mouseenter(function() { 
      $(this).css('opacity', '0.7'); 
      $(this).next().find('.mediumImg').addClass('zoomed'); 

     }); 
+0

@Bushan你能告訴我爲什麼closent不工作嗎? – designerNProgrammer

+0

@designerNProgrammer,因爲在DOM strusture中最接近的遍歷,即它看起來父母看到這個http://api.jquery.com/closest/ –

+0

@designerNProgrammer,很高興幫助你:) –

3

儘量選擇.next()兄弟和.find()從它的相關元素,

$(this).next('a').find('.mediumImg').addClass('zoomed'); 

的完整代碼會是這樣,

$('.overlayForCarDetails').mouseenter(function() { 
    $(this).css('opacity', '0.7'); 
    $(this).next('a').find('.mediumImg').addClass('zoomed'); 
}); 
2

你需要nextAll(),或siblings()獲得在a元素DOM層次樹中的同一級別。然後你需要使用find()得到.mediumImga的後裔closest()看起來是DOM層次結構元素的祖先。

$('.overlayForCarDetails').mouseenter(function() { 
    $(this).css('opacity', '0.7'); 
    $(this).next('a').find('.mediumImg').addClass('zoomed'); 
}); 

next()

描述:獲取每個元素的所有兄弟姐妹下列集合中的匹配元素,任選地通過一個選擇器過濾的。

+0

'mediumImg'是'了'孩子..看到HTML –

+0

確定@RajaprabhuAravindasamy,他有

Adil

+0

我剛剛格式化OP的html ..看看 –