【问题标题】:jQuery .each and height of divjQuery .each 和 div 的高度
【发布时间】:2012-07-18 08:41:00
【问题描述】:

我有这样的结构:

<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>

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

【问题讨论】:

标签: jquery height each


【解决方案1】:

您可以使用.map() 生成一个包含每个匹配元素高度的jQuery 对象(在这种情况下它实际上是一个数字数组)。然后,您可以将该数组applyMath.max 确定其中的最大值:

var maxHeight = Math.max.apply(Math, ​$(".b").map(function () {
    return $(this).height(); 
}));

这是working example


更新(这个应该完全按照您在问题中指定的行为)

$("div.a").each(function () {
    alert(Math.max.apply(Math, ​$("div.b", this).map(function () {
        return $(this).height(); 
    })));
});

这是另一个working example

【讨论】:

  • 由于问题是“在每个 div 类中设置为 a”,所以选择器应该是 $('.a').find('.b')
  • @spinningarrow 或简单的$('.a &gt; .b')
  • 重新阅读问题,我认为 OP 实际上想要单独的结果,每个 .a 元素一个。我会更新我的答案。
  • @nbrooks:嗯,是的。但是,Sizzle 从右到左工作,子选择器实际上比使用 .find() 慢 70%This place 有一些关于 jQuery 性能的非常好的信息。
  • @spinningarrow 谢谢你的链接,不知道。我只是认为 css 选择器总是优于不依赖本机方法的 jQuery 方法。很高兴知道!
【解决方案2】:
$('.a').each(function() {
    var maxHeight = 0;
    $('.b', this).each(function() {
        if($(this).height() > maxHeight) {
         maxHeight = $(this).height();  
        }
    });
    alert(maxHeight);
});

【讨论】:

  • 效果很好,但是如何为 clas a 中的每个 class b 设置局部最大高度?警报显示正确的值。
  • 只需添加$('.b', this).height(maxHeight)alert 当前所在的位置)-工作小提琴:jsfiddle.net/RZzTv
  • 感谢您的启发。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 2010-10-20
  • 2010-11-29
  • 2012-06-15
  • 2010-11-19
  • 1970-01-01
相关资源
最近更新 更多