- following code is working code used to find maximum height
$.fn.is used to add this method as jQuery Plugin.$.Map()return new arrayMath.Max.Applyreturn max number from array$.fn.tallest = function(outer, margins) { var fn = outer ? "height" : "outerHeight"; return Math.max.apply(Math, $.map(this, function(el){return $(el)[fn](margins);})); }; //var images=jquery(img 1.jpg, img 2.jpg, img 3.ipg, img 4.jpg); var slidesHeight = images.tallest();In this I have trouble understanding below line, but do understand how .Map() works.
$.map(this, function(el) {return $(el)[fn](margins);})$(el)[fn](margins)//Especially how this line return height attribute of image.
2 回答
$(el)[fn] is just another way of calling a method in $(el) whose name is not known in advance.
$(el)[fn](margins) is the same as having $(el).height(margins) or $(el).outerHeight(margins) depending on the value of the fn which depends on the value of the argument outer.
When outer is non-falsy, fn will be "outerHeight" and the above statement will be equivalent to $(el).outerHeight(margins)
When outer is falsy, fn will be "height" and the above statement will be equivalent to $(el).height(margins)
*Edited to incorporate Felix Kling's note.
Ok, let's break it down
$.map(this, function(el){return $(el)[fn](margins);})
$.mapis a function that iterates over a collection and performs the passed in function to each element within the collection and returns an array with all the results.
For example:$.map([1,2], function(i) {return i + 1}) [2, 3]The
thisrefers to the collection that the jQuery collection$.fn.tallest()is working against. For example:$('tr').tallest() // => this would refer to all the tr's within the dom$(el)[fn]
In JavaScript, you can either invoke a function bound to a receiver with the regular dot notation, such as$(e1).heightor you can use bracket notation as the example you provided does:$(e1)['height'].$(e1)[fn](margins)
marginsis the passed in argument to the functionheight().
Hope this helps.