基础知识
有两种不同的 jQuerymap()
功能:.map() http://api.jquery.com/map, and $.map() http://api.jquery.com/jQuery.map。他们执行类似的操作,但针对不同的集合。您使用的是第一个表单,它执行以下操作:
- 迭代调用该函数的 jQuery 对象(集合,无论什么)。在这种情况下,那就是
$(this)
,无论是.equalizeHeights()
函数被调用于...这是$('div')
: all <div>
页面上的元素(唷)。
-
Create an array with the same number of elements as the object that .map()
was invoked on (all divs on the page, remember) whose nth element is generated by invoking the provided callback - I'll get there in a sec - on the nth element in the targeted jQuery object. In this particular case, that callback is this function:
function(i, e) {
return $(e).height();
}
Yes, .map()
看起来确实像.each()
,但有一个关键的区别:
-
.each()
对集合中的每个元素执行操作;回调的返回值传递给.each()
用于判断是否继续迭代。
-
.map()
还对集合中的每个元素执行操作,但回调的返回值用于在返回的类数组对象中生成一个元素.map()
.
你还在吗?
jQuery 对象类似于数组,但它们不是数组!你打电话的原因.get()
在结束时.map()
调用的目的是将 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
}
但那又怎样呢constructor
商业?
正如你发现的那样,yes,一个是对象(jQuery 对象),另一个是数组。这就是为什么你需要它.get()
调用将类似数组的对象转换为Math.max()
可以理解。
而不是看着constructor
属性,您可以使用更多 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()
-他们。这样,您就可以看到整个对象图、它的所有属性等。
任何问题?评论走开。