2016-10-26 35 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 
    }); 
})