jQuery.each()

jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object

Description: 一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象迭代通过其命名属性。

  • version added: 1.0jQuery.each( collection, callback(indexInArray, valueOfElement) )

    collection遍历的对象或数组。

    callback(indexInArray, valueOfElement)每个成员/元素执行的回调函数。

$.each()函数和.each()是不一样的,这个是专门用来遍历一个jQuery对象。$.each()函数可用于迭代任何集合,无论是“名/值”对象(JavaScript对象)或阵列。在一个数组的情况下,回调函数每次传递一个数组索引和相应的数组值。(该值也可以通过访问this关键字,但是JavaScript将始终包裹this值作为一个Object ,即使它是一个简单的字符串或数字值。)该方法返回其第一个参数,这是迭代的对象。

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});

这将产生两个信息:

0: 52
1: 97

如果对象是作为集合使用,回调函数每次传递一个键值对的:

var map = { 
  'flammable': 'inflammable', 
  'duh': 'no duh' 
}; 
$.each(map, function(key, value) { 
  alert(key + ': ' + value); 
});

再次,这将产生两个信息:

flammable: inflammable
duh: no duh

我们可以打破$.each()返回使得回调函数在某一特定的迭代循环的false 。返回non-false是一样的一个continue在一个循环语句,它会立即跳转到下一个迭代。

Examples:

Example: Iterates through the array displaying each number as both a word and numeral

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  div#five { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
<script>
    var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };

    jQuery.each(arr, function() {
      $("#" + this).text("Mine is " + this + ".");
       return (this != "three"); // will stop running after "three"
   });

    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });
</script>

</body>
</html>

Demo:

Example: Iterates over items in an array, accessing both the current item and its index.

$.each( ['a','b','c'], function(i, l){
   alert( "Index #" + i + ": " + l );
 });

Example: Iterates over the properties in an object, accessing both the current item and its key.

$.each( { name: "John", lang: "JS" }, function(k, v){
   alert( "Key: " + k + ", Value: " + v );
 });
jQuery 1.6 API 中文版Clove整理、修订