返回值:jQueryeach(function(index, Element))

迭代一个 jQuery 对象,为每个匹配的元素执行函数。

.each() 方法可以让 DOM 循环结构变得更简单更不易出错。它会迭代 jQuery 对象中的每一个 DOM 元素。每次执行回调函数时,会传递当前循环次数作为参数(从 0 开始计数)。更重要的是,回调函数是在迭代时所处的那个 DOM 元素为上下文的语境中触发的。因此,关键字 this 总是指向当前正处于迭代的元素。

假设页面上有这样一个简单的无序列表:

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
  

我们可以选中并迭代这些列表项:

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});
  

下面列出的每条信息,就是在迭代列表的每一项时显示的信息:

0: foo
1: bar

我们可以通过返回 false 的方式,在回调函数内中止循环。

示例:

遍历三个 div 并设置它们的 color 属性。

<!DOCTYPE html>
<html>
<head>
<style>
  div { color:red; text-align:center; cursor:pointer; 
        font-weight:bolder; width:300px; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<div>Click here</div>
  <div>to iterate through</div>
  <div>these divs.</div>

<script>


    $(document.body).click(function () {
      $("div").each(function (i) {
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });


</script>
</body>
</html>

演示:

示例:

如果在迭代时不想使用普通的 DOM 元素,而是想获得对应的 jQuery 对象的话,请使用 $(this) 函数。例如:

<!DOCTYPE html>
<html>
<head>
<style>
  ul { font-size:18px; margin:0; }
  span { color:blue; text-decoration:underline; cursor:pointer; }
  .example { font-style:italic; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

To do list: <span>(click here to change)</span>
  <ul>
    <li>Eat</li>
    <li>Sleep</li>

    <li>Be merry</li>
  </ul>

<script>


    $("span").click(function () {
      $("li").each(function(){
        $(this).toggleClass("example");
      });
    });



</script>
</body>
</html>

演示:

示例:

可以使用 'return' 来提前结束 each() 循环。

<!DOCTYPE html>
<html>
<head>
<style>
  div { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<button>Change colors</button> 
  <span></span>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div id="stop">Stop here</div>
  <div></div>

  <div></div>
  <div></div>

<script>


    $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });



</script>
</body>
</html>

演示: