jQuery / Reference / .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>

예제 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>










