jQuery-不知道如何在使用.each时重置数组的最大值

jQuery - Not sure how to reset max value of array while using .each

本文关键字:数组 最大值 each 不知道 jQuery-      更新时间:2023-09-26

此处提供完整上下文:http://jsfiddle.net/dweiliu/bcHsy/1/

我目前有两个部分,这两个部分都有两个嵌套在自己文章中的表,如下所示:

<section>
    <article>
        <h2/>
        <table>...</table>
    </article>
    <article>
        <h2/>
        <table>...</table>
    </article>
</section>
<section>
    <article>
        <h2/>
        <table>...</table>
    </article>
    <article>
        <h2/>
        <table>...</table>
    </article>
</section>

我需要这种行为来处理每节3篇文章,等等…

$('section').each(function(){
    var heights = [];
    $('article').each(function(){
        heights.push($(this).find('table tr').length);
    });
    maxHeight = Math.max.apply(Math, heights);
    calculatedHeight = maxHeight * 35 + 35;
    $('article').css('height',calculatedHeight);
});

我希望能够浏览每个部分,查看该部分中的表格,找到长度最长的表格,并根据该长度计算高度。

现在,代码只遍历整个页面,一旦完成任何给定的部分,就不会重置数组高度的最大值。我知道我错过了什么。有人能给我指正确的方向吗?

我假设您的article s在section s内。如果是这样,您需要在每个section:的上下文中选择article s

$('section').each(function(){
    var heights = [];
    $('article', this).each(function(){
        heights.push($(this).find('table tr').length);
    });
    maxHeight = Math.max.apply(Math, heights);
    calculatedHeight = maxHeight * 35 + 35;
    $('article', this).css('height',calculatedHeight);
});

差异可能可以忽略不计,但你可能会看到这种替代方案是否更快:

$('section').each(function(){
    var max = 0;
    $('article', this).each(function(){
        max = Math.max(max, $(this).find('table tr').length);
    });
    var calculatedHeight = max * 35 + 35;
    $('article', this).css('height',calculatedHeight);
});