return biggest/highest object from jquery elements

跟風遠走 提交于 2019-12-12 03:37:55

问题


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



来源:https://stackoverflow.com/questions/13322582/return-biggest-highest-object-from-jquery-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!