我一直在玩这个jsfiddle,试图让我的头围绕它,但我不是在那里。 here是jsfiddle链接:
这里还有代码片段:
$.fn.equalizeHeights = function() {
var two = $(this).map(function(i,e) {
return $(e).height();
});
console.log(two);
console.log(two.constructor);
console.log(two.get());
console.log(two.get().constructor);
return this.height(Math.max.apply(this,two.get()));
}
$('input').click(function() {
$('div').equalizeHeights();
});
我看到他们正在使用prototype创建一个名为equalizeHeights()的函数来扩展jQuery。而$(this)表示页面上所有’div’元素的选择器。 map()调用遍历div数组中的每个项目并返回其高度?但是我所困惑的是我正在登录到控制台。
一个是一个对象,另一个是数组?
有人会在这段代码中详细说明map()和get()在做什么吗?
提前致谢。
解决方法
有两个不同的jQuery map()函数:.map()和$.map().它们执行类似的事情,但是在不同的集合中。您正在使用第一个表单,它执行以下操作:
>迭代调用该函数的jQuery对象(集合,无论如何)。在这种情况下,这是$(this),这是调用的.equalizeHeights()函数,它是$(‘div’):all< div>页面上的元素(hew)。
>创建一个与调用了.map()的对象相同数量的元素的数组(页面上的所有div,记住)通过调用提供的回调生成第n个元素 – 我将在一秒钟内到达 – 在目标jQuery对象的第n个元素上。在这种特殊情况下,该回调是这个功能:
function(i,e){
return $(e).height();
}
是的,.map()看起来像.each(),但有一个关键的区别:
> .each()对集合中的每个元素执行一个操作;传递给.each()的回调的返回值用于确定迭代是否继续。
> .map()还对集合中的每个元素执行一个操作,但是回调的返回值用于生成.map()返回的类似数组的对象中的一个元素。
你还在吗?
jQuery obects是数组的,但它们不是数组!在.map()调用结尾处调用.get()的原因是将该jQuery对象转换为一个真正的数组。该数组的元素是回调函数返回的值。
把它们放在一起
此函数设置每个单个< div>的高度。页面上最高的< div>的高度。就是这样:
$('input').click(function() { // bind a click listener to every <input> element
$('div').equalizeHeights(); // ...that will call the equalizeHeights() fn
// on all <div> elements when fired
});
所以,看看equalizeHeights()的定义:
$.fn.equalizeHeights = function() {
// construct an array that contains the height of every <div> element
var two = $(this).map(function(i,e) {
return $(e).height();
});
return this.height( // set the height of element <div> element to...
Math.max.apply( // the largest value in...
this,two.get() // the array of height values
)
); // ...and finally,return the original jQuery object to enable chaining
}
但是构造业务怎么样?
当你发现,是的,一个是一个对象(一个jQuery对象),另一个是一个数组。这就是为什么你需要.get()调用来将类似数组的对象转换成Math.max()可以理解的东西。
而不是查看构造函数属性,您可以使用更多的jQuery来确定您正在查看的内容:
console.log(two.jquery); // the version of jquery,something like "1.4.4" console.log($.isArray(two)); // is it a plain old JS array? false console.log(two.get().jquery); // undefined! it's just an array. console.log($.isArray(two.get())); // true
更好的是查看调试器内部的实际对象,而不仅仅是console.log()。这样,您可以看到整个对象图,其所有属性等。
任何问题?留下评论。