2012-09-18 25 views
0

我有類似這樣的標記內jQuery的回報和範圍內的每個()函數:的每一個()函數

<div class="imagegroup"> 
    <img> 
    <img> 
    <img> 
</div> 
<div class="imagegroup"> 
    <img> 
    <img> 
    <img> 
</div> 
<div class="imagegroup"> 
    <img> 
    <img> 
    <img> 
</div>​ 

而且我想單獨獲得各組中最高的圖像的高度。我有一個each函數中一個jQuery each功能:

$('.imagegroup').each(function(index) { 
    var tallestHeight = 0; 
    var slideshowNumber = index; 
    var slides = $(this).children(); 

    $(slides).each(function(index) { 
     thisSlideHeight = $(this).height(); 
     console.log("In slideshow #" + slideshowNumber + ", slide #" + index + " has height " + thisSlideHeight); 
     if (thisSlideHeight > tallestHeight) { 
      var tallestHeight = thisSlideHeight; 
     } 
     return tallestHeight; 
    }); 

    console.log("For slideshow " + slideshowNumber + " the tallest slide is " + tallestHeight); 

}); 

但我困惑的是如何通過內部各功能「一平」成「外」各功能無結果只是設置一個全局變量。因爲我寫了這個,所以tallestHeight保持爲零。我意識到這是超級初學者:)所有幫助非常感謝。

http://jsfiddle.net/m2aJu/

回答

2

你不需要return tallestHeight,刪除它,它會工作。

並將var tallestHeight = thisSlideHeight;改爲tallestHeight = thisSlideHeight;裏面第二個,你應該使用外部變量,而不是聲明一個新變量。

或者你可以簡化類似下面的代碼:

$('.imagegroup').each(function(index) { 
    var max = Math.max.apply(null, $(this).find('img').map(function() { 
     return $(this).height(); 
    }));   
    console.log("For slideshow " + index + " the tallest slide is " + max); 
}); 

And here is the working demo

+0

*** var *** tallestHeight = thisSlideHeight; – zerkms

+1

@zerkms是的,我看到'var' :) – xdazz

+0

稍微偏離主題,但仍然相關:只有javascript功能範圍,但沒有塊範圍。它也有提升,它將聲明顛倒到作用域的頂部(即函數),所以儘管從內部var應該從美學角度去除,但從技術上講,函數仍然保持不變:https://gist.github.com/ 3740886 – valentinas