简体   繁体   中英

How can I properly use jQuery to fix this fencepost case?

I have a function

function giveTheseEqualHeight ( selector )
{
     // selector: CSS selector of elements on the page to be forced to have the same height

     var these = $(selector);
     if (these.length < 2) return; 
     these.height('auto');
     var maxHeight = these.first().height();
     these.each(function(){
        var thisHeight = $(this).height();
        if (thisHeight > maxHeight) maxHeight = thisHeight;                
     });
     these.height(maxHeight);
}

which is very self explanatory.

Example use case:

giveTheseEqualHeight('.service-column h3'); 

would make all h3 elements that are descendants of elements of class service-column have equal height by heightening the ones that are smaller than the one with the most height.

The problem is that the loop

             these.each(function(){
                var thisHeight = $(this).height();
                if (thisHeight > maxHeight) maxHeight = thisHeight;                
             });

doesn't need to execute its body on the first iteration -- such amounts to useless operations. Instead of these.each , I want to start with the 2nd item. Is this possible?

jQuery has slice . Slice from second element (index 1). If the end is omitted, it slices until the end.

these.slice(1).each(...);

You can avoid calculating height of the first element if you get array of heights and then take the max with native Math.max:

function giveTheseEqualHeight(selector) {
    var these = $(selector);
    if (these.length < 2) return;
    these.height('auto');

    var maxHeight = Math.max.apply(null, these.map(function(el) {
        return $(this).height();
    }));
    these.height(maxHeight);
}

Here is a demo of it:

 function giveTheseEqualHeight(selector) { var these = $(selector); if (these.length < 2) return; these.height('auto'); var maxHeight = Math.max.apply(null, these.map(function(el) { return $(this).height(); })); these.height(maxHeight); } giveTheseEqualHeight('div') 
 div {display: inline-block;background: #EEE; vertical-align: top;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Lorem</div> <div>Test <br>rest</div> <div>Test <br> and rest <br>on the <br>west</div> 

Use the greater-than selector to select all elements who's index is greater than the number provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM