2012-09-11 50 views
2

我有這個的jsfiddle設置了我的問題:http://jsfiddle.net/7MjN6/使用`this`在一個循環的目標當前項目

正如你所看到的,我有兩個圖像。我想每個單擊的周圍的div都展開。我試圖使用this對象來確保單擊圖像只會擴展該圖像的div,但我確定我使用的是this錯誤,因爲它沒有連接。如果有人可以刺我的小提琴將非常感激!

HTML:

<body> 
    <div class="img-container"> 
     <a href="#"><img src="http://blueantlabs.com/wp-content/themes/blueantplate/img/port-wide/thefutureproject-605.png" /></a> 
    </div> 
    <div class="img-container"> 
     <a href="#"><img src="http://blueantlabs.com/wp-content/themes/blueantplate/img/port-wide/thefutureproject-605.png" /></a> 
    </div> 
</body>​ 

JS:

$(function(){ 
    $('.img-container').each(function(index){ 
     var imgHeight = $(" a img").height(); 
     $('a').click(function(e){ 
      e.preventDefault; 
      $('div').animate({height: imgHeight}); 
     }); 
    });  
});​ 
+2

你不使用'this'可言。我甚至搜索過你的代碼,零次出現的單詞「this」 – MrOBrian

+0

這是我的錯誤,沒有鏈接到最新的小提琴。 – alexvance

回答

3

試試這種方法。你並不需要.each都:

$(function() { 
    $('a').click(function(e) { 
     var imgHeight = $(this).find('img').height(); // use "this", find the img inside 
     e.preventDefault(); // this is a method, must use parentheses 
     $(this).parent().animate({ // "this" is the anchor; move up to the parent 
      height: imgHeight 
     }); 
    }); 
});​ 

http://jsfiddle.net/mblase75/7MjN6/4/

+0

非常感謝!我有一個後續問題:是否有更簡單的方法來切換回來比每次像這樣檢查div高度:http://jsfiddle.net/7MjN6/5/? – alexvance

+1

在改變之前使用['.data()'](http://api.jquery.com/data)存儲舊值。試一試,如果您需要更多幫助,請發佈一個單獨的問題。 – Blazemonger

0

您需要更改$("div").animate(...)$(this).closest("div").animate(...)。在事件處理程序this內引用點擊鏈接。你不想擴展所有div(你現在使用的版本);你想擴展包裝點擊鏈接的div。你使用.closest()導航到那個。

相關問題