2016-10-26 96 views
0

是否有收到任何区别(与性能或别的东西)的jQuery .each()element参数

$(".element").each(function(i, e){ 
    console.log("element: " + $(e)); 
}); 

并使用$(this)

$(".element").each(function(){ 
    console.log("element: " + $(this)); 
}); 

我已经做了几个测试,并以编程方式我没有发现任何区别。我总是使用$(this),因为它是大多数应用程序使用的标准。

+1

没有,有没有什么区别,'this'是缓存在这种情况下,元素,和'el'是一个普通的变量缓存元素的特殊变量,所以真的完全一样的东西。 – adeneo

回答

4

不,没有实际区别。在source of each,我们可以看到,同样的事情(obj[i])传递给call用作既this和您的回调中的第二个参数:

value = callback.call(obj[i], i, obj[i]); 
1

虽然没有在你的例子没有实际的区别,可用性e在封闭函数或方法调用中是一个有用的功能。

例如:

$('.element').each(function(i, e) { 
    $('.otherElement').text(function(index, element){ 

     // in this method, $(this) is an element from 
     // the $('.otherElement) collection (also $(element)); 
     // to access elements of the $(`.element') collection 
     // we can no longer use $(this), but we can still use 
     // $(e) (or e): 

     return $(e).eq(index).text(); // will set the text of the $(element) 
          // to the text of the $(e) element 
    }); 
})