return biggest/highest object from jquery elements

2019-09-17 02:20发布

问题:

Howdey!

Let's take a look at the following jQuery function:

$.fn.getMax = function() {
    return this.height(Math.max.apply(this, $(this).map(function(i, e) {
        return $(e).height();
    }).get()));
};

It returns and sets the heighest height for all selectors. But what is, if you want to return the object (not the height) with the heighest value?

So if you call the function like this:

$(selector).getMax().css({backgroundColor: "indigo"});

...how the element with the heighest height gets the backgroundColor?

UPDATE

I've managed it now with $.makeArray, as Amareswar said it.

$.fn.getMax = function(prop) {
    var max = $.makeArray($(this)).sort(function(a, b) {
        return (parseInt($(b).css(prop), 10) || 1) - (parseInt($(a).css(prop), 10) || 1);
    }).shift();
    return $(max);
};

Cheers!

回答1:

Try this:

$.fn.getMax = function() {
     /* create array of heights*/
    var heights = $(this).map(function(i, e) {
        return $(e).height();
    }).get();
    /* get max height*/
    var max = Math.max.apply(this, heights);
    /* get index of max in array*/
    var pos = $.inArray(max, heights)
    /* return element with proper index*/
    return this.eq(pos);
};

DEMO: http://jsfiddle.net/tTuE7/

EDIT : assumes you only want one element returned