jQuery获取子div的最大宽度

我需要在包装器div元素中获得子div的最大宽度(仅一个宽度)

 Math.max.apply(Math, $('.image').map(function(){ return $(this).width(); }).get()); 

根据建议,我会打破这个:

 $('.image').map(function(){ return $(this).width(); }).get(); 

以上获取所有.image div的列表,并将其转换为宽度列表。 所以你现在会有类似的东西: [200, 300, 250, 100, 400] 。 正如Felix指出的那样, .get()是获取实际数组而不是jQuery数组所必需的。

Math.max需要N个参数,因此您必须将其称为: Math.max(200, 300, 250, 100, 400) ,这是Math.max.apply部分完成的。

一个不那么困难的示例函数需要考虑; 不像cwolves那么优雅,但如果你是初学者,可能更容易理解。

 function getMaxChildWidth(sel) { max = 0; $(sel).children().each(function(){ c_width = parseInt($(this).width()); if (c_width > max) { max = c_width; } }); return max; } 

http://jsfiddle.net/userdude/rMSuJ/1/

我喜欢这种方法,因为它在核心可读性和短缺之间达到了最佳点(IMHO):

 var max_w = 0; $('#wrapper div.image').each(function() { max_w = Math.max(max_w, parseInt($(this).width())); }) 

YMMV当然。