use*_*598 50 javascript arrays jquery
有没有一种简单的方法从jQuery中的元素数组中找到min/max属性?
我经常发现自己根据最小和最大对应物动态调整元素组.大多数情况下,这与元素的宽度和/或高度有关,但我确信这可以应用于元素的任何属性.
我通常做这样的事情:
var maxWidth = 0;
$('img').each(function(index){
if ($(this).width() > maxWidth)
{
maxWidth = $(this).width();
}
});
Run Code Online (Sandbox Code Playgroud)
但似乎你应该能够做到这样的事情:
var maxWidth = $('img').max('width');
Run Code Online (Sandbox Code Playgroud)
这个功能是否存在于jQuery中,或者有人可以解释如何创建这样做的基本插件?
谢谢!
nav*_*een 75
使用快速JavaScript Max/Min - John Resig
示例有谷歌,雅虎和宾的三个标志.
HTML
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" alt="Google Logo" /><br/>
<img src="http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png" alt="Yahoo Logo" /><br/>
<img src="http://www.bing.com/fd/s/a/h1.png" alt="Bing Logo" />
Run Code Online (Sandbox Code Playgroud)
使用Javascript
$(document).ready(function(){
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};
// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
//updated as per Sime Vidas comment.
var widths= $('img').map(function() {
return $(this).width();
}).get();
alert("Max Width: " + Array.max(widths));
alert("Min Width: " + Array.min(widths));
});
Run Code Online (Sandbox Code Playgroud)
PS:jsfiddle在这里
amr*_*amr 15
您可以apply在OO的上下文之外使用,无需扩展原型:
var maxHeight = Math.max.apply( null,
$('img').map(function(){ return $(this).height(); }).get() );
Run Code Online (Sandbox Code Playgroud)
看看计算插件,也许它可以帮助你解决你的问题。它们提供了许多数学函数,例如 DOM 元素上的 min、max 和 avg。
例子:
$("input[name^='min']").min();
$("input[name^='max']").max();
Run Code Online (Sandbox Code Playgroud)