티스토리 뷰

Web/jQuery

jQuery API - .each()

부라더#수 2016. 1. 7. 00:56

오늘은 jQuery API Document 의 .each() 함수에 대해서 이야길 나눠보고자 합니다


16.01.05 프로젝트 작업 중 기존의 방식과 조금 다르게 코딩을 시도하였는데, 


그 페이지에서 사용된 .each() 함수에 대해 알아보겠습니다


(자세한 페이지의 내용과 예제를 보시고 싶으시면, project 카테고리의 16-01-06 포스팅을 참고하세요)






.each( function(index, Element) )


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

사용 : DOM의 기본 Loop 개념을 간결하고 쉽게 사용, 오류 발생을 최소화 할 수 있다

문법 : .each( function(index, Element) ) { 실행 함수 } 

설명 : .each() 함수는! DOM 요소들 (Document Object Model ; 문서객체모델), 즉 jQuery 객체들을 위한 반복 로직을 처리하기 위해 만들어졌습니다. 초기 인덱스(Index) 값을 0으로 잡고 콜백 함수가 실행 됩니다





요약하자면 .each() 함수는 jQuery 객체의 수만큼 반복 로직을 수행하게 되는데, 음...for문을 떠올리시면 쉽겠네요

가령 index=0부터 Element의 수만큼 반복되는 실행 구문을 for문으로 표현하면


for (int i=0 ; i<=Element ; i++){

   반복 실행 구문

}


이런 형태가 될텐데, 이러한 반복 구문을 .each() 함수를 통해 쉽게 구현해 낼 수 있습니다




원문 (http://api.jquery.com/each/)에 소개된 예제를 통해 확인 해 보겠습니다


<ul>

   <li>foo</li>

   <li>bar</li>

</ul>




위와 같은 마크업에 접근하여 li 안에 있는 텍스트를 찍어보는 스크립트를 짜보겠습니다


$('li').each(function(index) {

    alert(index + ': ' + $(this).text());

});



그 결과는, 아래와 같이 나오네요


0 : foo

1 : bar



필요에 따라 if 문으로 분기하여 false; 를 리턴하시면 중간에 콜백 함수의 실행을 멈출 수도 있습니다

아래 예제를 보겠습니다




1) 예제코드


<!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>


1) 결과보기 (아래 버튼을 클릭해보세요)





다음은 $(this)와 같이 사용하여 일반적인 DOM 요소가 아닌 jQuery 객체로 제어해 보겠습니다


2) 예제코드


<!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>


2) 결과보기






만약, .each() 함수의 반복 진행을 멈추고 싶다면 아래 예제 코드와 같이 false를 리턴하시면 됩니다


3) 예제코드


<!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>


3) 결과보기 (아래의 Change colors 버튼을 클릭해 보세요)






위의 소스코드를 잠시 살펴보자면, div만큼 루프를 돌다가 div의 id 값이 #stop 일때 return false; 를 통해서 each() 함수를 빠져나오게 됩니다

마치 while{  break; } 에서와 같이 말이죠


기본적으로 for문이나 while 문이 있는데 이게 얼마나 쓰일까? 라고 생각하실 수도 있겠습니다만

때에 따라 item 의 개수를 굳이 .length로 count하지 않아도 사용 할 수 있으니 생각보다는 활용도가 높지 않을까 생각합니다

각자 프로그래밍 할때 한번쯤 적용해 보시는 건 어떨까요!

이상 .each() 함수에 대해 전반적으로 알아보았습니다^^






위의 예제는 모두 http://www.jquery.com 의 document에 수록 되어있는 내용임을 밝힙니다

댓글