0
  • following code is working code used to find maximum height
  • $.fn. is used to add this method as jQuery Plugin.
  • $.Map() return new array
  • Math.Max.Apply return 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.

4

2 回答 2

1

$(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)

于 2013-02-22T13:56:26.047 回答
0

*Edited to incorporate Felix Kling's note.

Ok, let's break it down

$.map(this, function(el){return $(el)[fn](margins);})
  1. $.map is 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]
    
  2. The this refers 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
    
  3. $(el)[fn]
    In JavaScript, you can either invoke a function bound to a receiver with the regular dot notation, such as $(e1).height or you can use bracket notation as the example you provided does: $(e1)['height'].

  4. $(e1)[fn](margins)
    margins is the passed in argument to the function height().

Hope this helps.

于 2013-02-22T14:03:34.770 回答