从jquery元素返回最大/最高对象 [英] return biggest/highest object from jquery elements
本文介绍了从jquery元素返回最大/最高对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Howdey!
让我们看一下下面的jQuery函数:
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()));
};
它返回并设置所有选择器的最高度.但是,如果要返回最大值的object
(而不是高度)是什么?
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"});
...高度最高的元素如何获得backgroundColor
?
...how the element with the heighest height gets the backgroundColor
?
更新
我现在已经使用$.makeArray
对其进行了管理,例如 Amareswar 说.
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);
};
干杯!
推荐答案
尝试一下:
$.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);
};
演示: http://jsfiddle.net/tTuE7/
假定您只希望返回一个元素
EDIT : assumes you only want one element returned
这篇关于从jquery元素返回最大/最高对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文