Javascript 从jquery元素返回最大/最高的对象
你好 让我们看一下以下jQuery函数:Javascript 从jquery元素返回最大/最高的对象,javascript,jquery,size,height,Javascript,Jquery,Size,Height,你好 让我们看一下以下jQuery函数: $.fn.getMax = function() { return this.height(Math.max.apply(this, $(this).map(function(i, e) { return $(e).height(); }).get())); }; 它返回并设置所有选择器的最高高度。但是,如果您想返回具有最高高度值的对象(而不是高度),又是什么呢 因此,如果您像这样调用函数: $(selector).ge
$.fn.getMax = function() {
return this.height(Math.max.apply(this, $(this).map(function(i, e) {
return $(e).height();
}).get()));
};
它返回并设置所有选择器的最高高度。但是,如果您想返回具有最高高度值的对象(而不是高度),又是什么呢
因此,如果您像这样调用函数:
$(selector).getMax().css({backgroundColor: "indigo"});
…高度最高的元素如何获得背景色
更新
我现在已经用$.makeArray
管理了它
干杯 试试这个:
$.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);
};
演示:
编辑:假设您只希望返回一个元素您还没有问任何问题……只是提供了一些毫无意义的代码,将“返回此”作为最后一个元素statement@charlietfl添加了如何
和?
;-)@Amareswar返回此
,但不起作用。在这种情况下,您应该通过将元素作为参数传递来编写类似$.makeArray的静态函数。这是一种不错的方法,但我现在已经按照Amareswar所说的方法处理了它。不过,谢谢!:-*
$.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);
};