본문 바로가기

Web Application/jQuery

[jQuery] jQuery의 반복문(each문 사용법)

Insert title here

jQuery의 반복문-each문 사용방법

- each문은 jQuery의 객체의 수만큼 반복하는 함수입니다.
사용 방법
$('.....').each(function(index){
	..........(선택된 객체에 실행될 함수 구현)
})
- 예제를 통하여 더 쉽게 알아봅시다.
<ul>
	<li>One-Element</ll>
	<li>Two-Element</ll>
</ul>

<script type="text/javascript">
	$('li').each(function(index){
		alert(index + ' , ' + this.text());
	});
</script>
실행 결과
0 , One-Element
1 , Two-Element
- 존재하는 </li>들을 반복하면서 text만을 가져오도록 한 것입니다.
- index는 0부터 !

응용 방법

-32,531 20,000 15,321 -24,200 1,000
-2,531 6,200 10,333 20,200 152,000
9,531 -9,103 1,331 2,200 15,000
12,531 -2,020 -321 44,240 18,910
- (-)부호가 붙은 숫자는 (-)부호 대신 ▼와 빨간색으로 색상 변경
- 나머지 숫자들은 ▲과 초록색으로 색상 변경
- 구현 방법
$("td").each(function(){
		if($(this).text().indexOf('-') > -1){
			$(this).text($(this).text().replace('-','▼'));
			$(this).css("color","red");
		}else{
			$(this).prepend('▲');
			$(this).css("color","green");
		}
})
- 만일 특정한 칸만 바뀌길 원한다면 <td> 태그에 name속성(ex.name="test") 지정 후 $("td") 대신 $("td[name="test"]")로 한다면 name 속성을 준 곳만 적용된다.
- 매우 많이 쓰이는 함수로서, 꼭 습득하여 유연하게 사용 가능하도록 하면 좋을 거 같습니다.