查询jQuery's $(selector).each() 'element'参数vs $(th

Difference between getting jQuery's $(selector).each() 'element' parameter, vs $(this)

本文关键字:th vs 参数 element selector jQuery 查询 each      更新时间:2023-09-26

获得jQuery .each()element参数是否有任何差异(与性能或其他方面有关)

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

和使用$(this) ?

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

我做了几次测试,在编程上我没有注意到任何差异。我一直使用$(this),因为它是大多数应用程序使用的标准。

不,没有实际区别。在each的源代码中,我们可以看到同样的东西(obj[i])被传递给call,用作this和回调中的第二个参数:

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

虽然在您的示例中没有实际差异,但在封闭的函数或方法调用中使用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
    });
})