[jQuery] .each()

2021-01-17

jQuery / Method / .each() - 선택한 요소 각각에 대하여 함수를 실행시키는 메서드

.each()

.each()는 선택한 요소가 여러 개일 때 각각에 대하여 반복하여 함수를 실행시킵니다.

  • 문법

.each( function ) 특정 조건을 만족할 때 반복 작업에서 빠져려면

return false 를 사용합니다.

  • 예제 1

p 요소에 각각 다른 클래스를 추가합니다.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      .s1 {color: red;}
      .s2 {color: blue;}
      .s3 {color: green;}
      .s4 {color: brown;}
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        var i=1
        $( 'p' ).each( function() {
          $( this ).addClass( 's' + i );
          i = i + 1;
        } );
      } );
    </script>
  </head>
  <body>
    <p>Lorem</p>
    <p>Ipsum</p>
    <p>Dolor</p>
    <p>Amet</p>
  </body>
</html>

jQuery-each-01

  • 예제 2

반복 작업을 두번만 하고 빠져나옵니다.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      .s1 {color: red;}
      .s2 {color: blue;}
      .s3 {color: green;}
      .s4 {color: brown;}
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        var i=1
        $( 'p' ).each( function() {
          $( this ).addClass( 's' + i );
          i = i + 1;
          if ( i == 3 ) {
            return false;
          }
        } );
      } );
    </script>
  </head>
  <body>
    <p>Lorem</p>
    <p>Ipsum</p>
    <p>Dolor</p>
    <p>Amet</p>
  </body>
</html>

jQuery-each-02

출처 : [https://www.codingfactory.net/10312]