each

« Обратно на страницу Ядро jQuery


each( вызов )

Выполняет функцию для каждого элемента набора. Это означает, что каждый раз, когда выполняется указанная функция (а выполняется она один раз для каждого совпавшего элемента) ключевое слово ‘this’ указывает на конкретный элемент DOM. Помните, что слово ‘this’ НЕ указывает на объект jQuery. Кроме того, запущенная функция передает единственный аргумент, который показывает позицию элемента в составе набора совпавших элементов (integer, отсчет с 0).

Возврат ‘false’ в рамках каждой функции полностью прерывает цикл по всем элементам (подобно оператору break в обычном цикле).

Возврат ‘true’ в цикле останавливает текущую итерацию и переходит в начало цикла для следующей итерации (подобно оператору continue в обычном цикле).

Аргументы:
вызов Функция

Функция, выполняющаяся для каждого совпавшего элемента.

function callback(index, domElement) {
  this; // this == domElement
}
Примеры:

Изменяет цвет текста для трех элементов div

    $(document.body).click(function () {
      $("div").each(function (i) {
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>

  $(document).ready(function(){

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

  div { color:red; text-align:center; cursor:pointer;
        font-weight:bolder; width:300px; }
  </style>
</head>
<body>
  <div>Click here</div>
  <div>to iterate through</div>

  <div>these divs.</div>
</body>
</html>

Если Вы хотите использовать объект jQuery вместо обычного элемента DOM, то пользуйтесь функцией $(this), например:

    $("span").click(function () {
      $("li").each(function(){
        $(this).toggleClass("example");
      });
    });
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){

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

  });
  </script>

  <style>
  ul { font-size:18px; margin:0; }
  span { color:blue; text-decoration:underline; cursor:pointer; }
  .example { font-style:italic; }
  </style>
</head>
<body>
  To do list: <span>(click here to change)</span>

  <ul>
    <li>Eat</li>
    <li>Sleep</li>
    <li>Be merry</li>

  </ul>
</body>
</html>

Для остановки циклов each() можно использовать ‘return’.

    $("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;
        }
      });
    });
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){

    $("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>

  <style>
  div { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }
  </style>
</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>
</body>
</html>
Name Type

Установите значение TRUE для отмены всех переменных jQuery.