jQuery .each和div的高度

ple*_*was 2 each jquery height

我有这样的结构:

<div class="a">
  <div class="b"></div>
  <div class="b"></div>
 <div class="b"></div>
 <div class="b"></div>
</div>
<div class="a">
  <div class="b"></div>
  <div class="b"></div>
</div>
<div class="a">
  <div class="b"></div>
  <div class="b"></div>
  <div class="b"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我想在每个div类中设置为a的类设置为b的最高div,并在alert中显示?

Jam*_*ice 6

您可以使用.map()生成jQuery对象(在本例中它实际上是一个数字数组),其中包含每个匹配元素的高度.然后apply,您可以使用该数组来Math.max确定其中的最大值:

var maxHeight = Math.max.apply(Math, ?$(".b").map(function () {
    return $(this).height(); 
}));
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.


更新(这个应该与您在问题中指定的完全相同)

$("div.a").each(function () {
    alert(Math.max.apply(Math, ?$("div.b", this).map(function () {
        return $(this).height(); 
    })));
});
Run Code Online (Sandbox Code Playgroud)

这是另一个工作示例.

  • @nbrooks:嗯,是的.但是,Sizzle从右到左工作,而子选择器实际上比使用`.find()`大约低70%**.[这个地方](http://addyosmani.com/jqprovenperformance/)有一些关于jQuery性能的非常好的信息. (2认同)

bil*_*can 5

$('.a').each(function() {
    var maxHeight = 0;
    $('.b', this).each(function() {
        if($(this).height() > maxHeight) {
         maxHeight = $(this).height();  
        }
    });
    alert(maxHeight);
});
Run Code Online (Sandbox Code Playgroud)