LinkedNestBlog

[jQuery] .each() - 루프의 사용

by jinwon lee

[jQuery] .each() - 루프의 사용


.each(function(index, Element)) 

 

URL: http://api.jquery.com/each/

 

Description: Iterate over a jQuery object, executing a function for each matched element.  

 

설명: 각 엘리먼트에 매치되는 function을 수행하는 JQuery 객체 상에서 반복한다.

 

function(index, Element)은?

: 매치되는 엘리먼트에 대해 실행하는 함수(function).

 

 The .each() method is designed to make DOM looping constructs concise and less error-prone.

 When called it iterates over the DOM elements that are part of the jQuery object.

 Each time the callback runs, it is passed the current loop iteration, beginning from 0. 

 More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

 

 

 

아래와 같은 html ul태그의 li태그 내의 text(foo, bar)를 사용하고 싶다면 


 <ul>

<li>foo</li>

<li>bar</li>

</ul>

아래와 같이 한다.

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

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

});

위의 결과로 아래와 같이 각각의 내용이 alert창으로 두번 출력하게 된다.

 

0: foo
1: bar