2012-11-10 33 views
0

Howdey!返回来自jquery元素的最大/最高对象

让我们来看看下面的jQuery函数:

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

它返回,并为所有选择的heighest高度。但是,如果你想返回最高值的object(而不是高度)?

所以,如果你喜欢这样的功能:

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

...与heighest高度元素如何获取backgroundColor

UPDATE

我和$.makeArray管理,现在,作为Amareswar说。

$.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); 
}; 

干杯!

+0

你还没有问一个问题...只是提供了一些代码,使无sense – charlietfl

+0

'return this'作为最后一条语句 – Amareswar

+0

@charlietfl添加了'how'和'?';-) – yckart

回答

0

试试这个:

$.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/

编辑:假设你只想要一个元素返回

+0

不错的方法,但我现在就像Amareswar说的那样管理它。但是,谢谢! : - * – yckart