본문 바로가기
프로그래밍/jQuery

jQuery API 정복 - 선택된 요소만큼 루프, each()

by zoo10 2011. 4. 28.

.each()

원문 링크 http://api.jquery.com/each/

.each( function(index, Element) )Returns : jQuery

개요 : jQuery 객체 만큼 반복하고, 선택된 요소들에 함수를 실행합니다.

  • .each( function(index, Element) )
  • function(index, Element) 선택된 요소에 실행될 함수

.each() 함수는 DOM의 기본 Loop 개념을 간결하고 최소한의 오류 발생을 위해 만들어 졌습니다. DOM 요소들 즉, jQuery 객체들을 위해 반복 로직을 처리하기 위해 만들어졌습니다. 0 을 인덱스의 초기값으로 하여 콜백 함수가 실행됩니다. 더 눈여겨 봐야 할 것은, this키워드를 사용하면 현재 콜백되고 있는 DOM 요소에 어떤 작업을 할 수 있게 됩니다.

제가 써놓고도 뭔 소린지 모르겠네요. ㅎㅎ;;; 간단히 줄이면 .each()함수는 jQuery 객체의 수만큼 for 문 같이 반복을 해주는 함수입니다. 아주 편리하게 사용이 되요. 아래 간단한 예를 보시면 아~ 하실겁니다.

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

아주 간단한 마크업입니다. 자 이 리스트에 접근하여 li 안에 있는 텍스트를 찍어보는 스크립트를 짜보겠습니다.

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

0: foo
1: bar

뭐야 별거 아니잖아. 하고 계시죠? ㅎㅎ 아주 간단하지만 아주 유용해 보입니다.

만약 콜백 함수의 실행을 멈추고 싶으시면 false 를 리턴하시면 됩니다. 와우 이건 또 이대호 도루하는 소리?? 맨 아래 예제에 이에 대한 내용이 있습니다. 그때 확인하시죠~~

예 제  
클릭하면 3개의 div의 색깔을 바꿔줍니다.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; text-align:center; cursor:pointer; 
        font-weight:bolder; width:300px; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.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>

미리보기

클릭해 보세요. 색깔이 바뀝니다. 아주 간단하게 3개의 div태그의 텍스트 색을 바꿀 수 있습니다. 뭐 이정도는 걍 짜도 금방이라구요? 글킨 합니다. ^^;;

 

예 제  
$(this)와 같이 사용하여 일반적인 DOM 요소가 아닌 jQuery 객체로 제어해 보기

<!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="http://code.jquery.com/jquery-1.5.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>

미리보기

뭐 예제 설명은 거창하지만 this 키워드를 사용해서 현재 콜백 함수가 적용중인 요소를 제어할 수 있다는 내용입니다.

 

예 제  
each 함수의 반복 진행을 멈추고 싶다면 false를 리턴하세요.

<!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="http://code.jquery.com/jquery-1.5.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>

미리보기

div만큼 루프를 돌다가 현재의 div의 id값이 'stop'이라면 false를 리턴합니다. false가 리턴되는 순간 each() 함수를 빠져나오게 되네요. 마치 일반 while문의 break같은 겁니다.

 

이번 함수는 참 실용적입니다. 점점 재미있는 함수들이 소개되고 있습니다. 잘 사용해 보세요.

그럼 즐프하세요.

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.