【问题标题】:In jQuery, what's the difference between these $.each declarations? [duplicate]在 jQuery 中,这些 $.each 声明之间有什么区别? [复制]
【发布时间】:2014-04-10 06:58:32
【问题描述】:

我以前用过这两种方法,但我不确定有什么区别。有人可以解释这些差异吗?

1. $(myObjects).each(function(){}};

2. $.each($(myObjects), function(){});

【问题讨论】:

标签: jquery


【解决方案1】:

jQuery 对象迭代器

$('.myClass, .anotherClass').each(function(){}};

这是从您的选择器循环遍历每个 jquery 元素。

来自文档:

遍历一个 jQuery 对象,为每个匹配的元素执行一个函数。 $.each() 函数与 $(selector).each() 不同,后者用于以独占方式迭代 jQuery 对象。

.each() docs


通用迭代器

var arr = [1,2,3,4];
$.each(arr, function(index, value){});

这是一种循环数组或对象的实用方法。

来自文档:

通用迭代器函数,可用于无缝迭代对象和数组。具有长度属性的数组和类数组对象(例如函数的 arguments 对象)通过数字索引进行迭代,从 0 到 length-1。其他对象通过其命名属性进行迭代。

$.each() docs


区别:

您可以同时使用:$.each() 和 .each() 来循环 jQuery 对象列表。

// Can be used to iterate any list or object
var $selectedElements = $('.tabs');
$.each($selectedElements, function(index, value){
    $(this).html(index);
});

// Can only be used for iterating a list of jquery objects, 
//  and is the recommended way of doing it.
$selectedElements.each(function(index, element){
    $(this).html(index);

});

但是你不能使用 .each() 来循环一个对象或列表

// YOU CANNOT DO THIS
var list = [1,2,3];
list.each(function(){

});

【讨论】:

  • @Weblurk 不客气 :)
【解决方案2】:

来自docs

$.each() 函数与 .each() 函数不同,后者用于 专门迭代一个 jQuery 对象。 $.each() 函数可以 用于迭代任何集合,无论是地图 (JavaScript 对象)或数组。

【讨论】:

    【解决方案3】:

    .each 是一个迭代器,仅用于迭代 jQuery 对象集合,而 jQuery.each ($.each) 是用于迭代 javascript 对象和数组的通用函数。

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2016-05-08
      • 2010-09-18
      • 2021-04-19
      • 2020-07-22
      相关资源
      最近更新 更多