两者都是可以同遍历jQuery对象与非jQuery对象的方法,基本使用如下:
var li = $("li");
li.each(function(index,element){
console.log(index);
console.log($(this).text());
}
);
var array = [1,2,3,4,5];
$.each(array, function(index,element){
console.log(index+','+element);
});
在这里讲一下其中的function()方法,该方法中,
参数不需要一定写成(index,element),写成其他的,执行时也会按照顺序代表对应的值,甚至可以不写参数或者只写一个参数,此时运行结果:
var li = $("li");
li.each(function(){
console.log($(this).text());
}
);
//运行结果:
//Link 1
//Link 2
//Link 3
var array = [1,2,3,4,5];
$.each(array, function(a){
console.log(a);
});
//运行结果:
//0
//1
//2
//3
//4
即没有传入参数的时候就无法直接引用对应的(index,element),但是还可以通多this得到,this与element是一样的,都代表对应DOM元素:
var li = $("li");
li.each(function(index, element){
console.log(this == element);
}
);
//运行结果:
//true
而传入一个参数的时候,还是按顺序,代表对应的值,即只有index,无法直接引用element的值了,但是跟上面的例子一样还是可以通过$(this)
来得到。
当然,传入三个参数的时候就会显示undefined啦,因为function方法根本就没有这个参数。
最后,提一下这个function中的第二个参数,既然this与element是一样的,那为什么需要第二个参数即element呢?
官方文档是这样解释的:
Whether intentional or inadvertent, the execution context may change.
When consistently using the keyword this, it’s easy to end up
confusing ourselves or other developers reading the code. Even if the
execution context remains the same, it may be more readable to use the
second parameter as a named parameter. For example:$( "li" ).each( function( index, listItem ) { this === listItem; // true // For example only. You probably shouldn't call $.ajax() in a loop. $.ajax({ success: function( data ) { // The context has changed. // The "this" keyword no longer refers to listItem. this !== listItem; // true } }); });
就是说某些情况下两者是等效的,差别在于:一个是代码可读性的差别,使用element显然表达更明确一些,另一个是当与$.ajax()一起使用的时候,this无法表示element了,此时传进一个element就很有必要了。