2011-11-22 85 views
3

使用jQuery選擇列表的最高圖像最簡單的方法是什麼?選擇列表中最高的圖像

結構:

<ul class="gallery"> 
    <li><img width="100px" height="300px" src="1.jpg"></li> 
    <li><img width="100px" height="200px" src="2.jpg"></li> 
    <li><img width="100px" height="500px" src="3.jpg"></li> 
</ul> 

回答

5
// use anonymous function to prevent clutter of the scope 
(function() { 
    var max_height = 0; 
    var image = null; 

    $('.gallery li img').each(function() { 
     var cur_height = $(this).height(); 
     if (cur_height > max_height) { 
      max_height = cur_height; 
      image = this; 
     } 
    }); 

    // just an example 
    $(image).addClass('tallest'); 
})(); 
+2

如果裏面有'.gallery'沒有IMG元素,你的代碼將扔'image.addClass'(因爲'image'是'null') 。所以,相反,你想'image = this;'在迭代中,然後''(image).addClass'永遠不會拋出... –

+1

另外,考慮緩存'$(this).height()'在一個變量,這樣不會不必要地計算兩次。 –

3
var height = 0, 
    img = null; 
$('img','.gallery').each(function() { 
    var h = $(this).height(); 
    if (h > height) { 
     height = h; 
     img = this; 
    } 
}); 

// img is the tallest image