Javascript $.Map() 和 Math.Max.Appy() 来查找最大高度

Javascript $.Map() & Math.Max.Appy() to find maximum height

本文关键字:查找 高度 Appy Math Map Javascript Max      更新时间:2023-09-26
  • 以下代码是用于查找最大高度的工作代码
  • $.fn.用于将此方法添加为 jQuery 插件。
  • $.Map()返回新数组
  • Math.Max.Apply从数组返回最大数量

    $.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();
    
  • 在这一点上,我很难理解以下行,但确实理解如何。地图(( 有效。
    $.map(this, function(el) {return $(el)[fn](margins);})

  • $(el)[fn](margins)//特别是这条线如何返回图像的高度属性。

$(el)[fn]只是在$(el)中调用方法的另一种方法,该方法

的名称事先并不知道。

$(el)[fn](margins) 与具有 $(el).height(margins)$(el).outerHeight(margins) 相同,具体取决于fn的值,而的值取决于参数outer的值。

outer是非伪造的时,fn将被"outerHeight",上述陈述将等同于$(el).outerHeight(margins)

outer是伪造的时,fn将被"height",上述陈述将等同于$(el).height(margins)

*经过编辑以纳入Felix Kling的注释。

好的,让我们分解一下

$.map(this, function(el){return $(el)[fn](margins);})
  1. $.map 是一个函数,它遍历集合,并对集合中的每个元素执行传入函数,并返回包含所有结果的数组。
    例如:

    $.map([1,2], function(i) {return i + 1})
    [2, 3]
    
  2. this是指 jQuery 集合$.fn.tallest()正在处理的集合。例如:

    $('tr').tallest() // => this would refer to all the tr's within the dom
    

  3. $(el)[fn]在 JavaScript 中,您可以使用常规点表示法调用绑定到接收器的函数,例如 $(e1).height,也可以像您提供的示例一样使用括号表示法:$(e1)['height'] .


  4. $(e1)[fn](margins) margins 是传递给函数 height() 的 in 参数。

希望这有帮助。