选择列表的最高图像

roo*_*ofl 3 jquery image jquery-selectors

使用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>
Run Code Online (Sandbox Code Playgroud)

Pee*_*Haa 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');
})();
Run Code Online (Sandbox Code Playgroud)

  • 如果`.gallery`中没有IMG元素,你的代码将抛出`image.addClass`(因为`image`是'null`).所以,你需要`image = this;`在迭代中,然后`$(image).addClass`从不抛出... (2认同)