JQuery获得最高的孩子身高并放入父元素

Dan*_*der 5 javascript math jquery jquery-plugins

在上一个问题中,我<li>在页面上的UL组中为各个标签设置了相等的高度.但是现在我意识到为了更好的主题,我想<li>在UL组中的一组标签上设置最高的高度,并将其设置为其各自的父<ul>本身,以便更好地对我的页面进行主题化.我在这里有一个新的小提琴,我试图<li>在UL组中找到最高的高度并将其设置为UL.

问题仍然是特异性.第<li>一个UL组的最高高度被设置为<ul>页面上的所有标签.<li>UL组(第1行)中最高的高度为260px,第2行的高度为156px.但是,仍然会在页面上的两个UL标签上设置260px.UL将在页面上增长,因此我希望代码是可扩展的,而无需在JQuery中指定每一行.到目前为止,我试过这个:

// get the height of the tallest LI within each UL group
    var max = Math.max.apply(Math, $(".item-list ul li").map(
        function(){
          return $(this).height();
        }
      ));

// now render the height in each parent UL

    $(".item-list ul").each(function() {
      $(this).find(".item-list ul").height(max);
    });
Run Code Online (Sandbox Code Playgroud)

......但第二部分不起作用.这有效但......

$(".item-list ul").height(max);
Run Code Online (Sandbox Code Playgroud)

...它将最高的高度<li>放在所有UL标签的页面上.理想情况下,最终的HTML应该是:

<div class="item-list row-1">
<ul style="height: 260px;">
etc...

<div class="item-list row-2">
<ul style="height: 156px;">
etc...
Run Code Online (Sandbox Code Playgroud)

工作版本基于这一个低于

I H*_*azy 12

如果我理解正确,你应该max.each()循环中进行操作.

function thisHeight(){
    return $(this).height();
}

$(".item-list ul").each(function() {
    var thisULMax = Math.max.apply(Math, $(this).find("li").map(thisHeight));
    $(this).height(thisULMax);
});
Run Code Online (Sandbox Code Playgroud)

我还将map函数设置为命名函数,以便您可以重用它.


以下是一些更清洁的解决方案.

这个传递一个函数来height()使用它作为迭代器.稍微缩短一点.

function thisHeight(){
    return $(this).height();
}

$(".item-list ul").height(function() {
    return Math.max.apply(Math, $(this).find("li").map(thisHeight));
});
Run Code Online (Sandbox Code Playgroud)

这是另一种使用方式.reduce(),虽然IE8需要垫片以及更低.

function maxHeight(max, elem) {
    var h = $(this).height();
    return max > h ? max : h;
}

$(".item-list ul").height(function() {
    return $(this).find("li").toArray().reduce(maxHeight, 0);
});
Run Code Online (Sandbox Code Playgroud)