티스토리 뷰

WEB/jQuery

[jQuery] 요소의 반복 each()

춘햄 2021. 6. 7. 11:14

each() 함수는 마치 for문처럼 특정 요소를 만날 때마다 반복적으로 수행할 함수를 작성할 수 있는 함수이다.

이를 이용하여 특정 태그를 만날 때마다 index 번호를 해당 태그에 순차적으로 할당해줄 수 있다.

바로 예제를 확인해보자.


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>요소만큼 반복해서 속성 설정 및 가져오기</title>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
			// each() : for() 처럼 반복 함수
			// 요소.each(function(index)){반복해서 실행할 내용})
			// 요소를 찾을 때마다 index가 자동으로 증가!
			
			// <p> 태그에 구별할 수 있는 id 를 부여 : attr()
			$('p').each(function(index) {
				$(this).attr({
					id : "para_" + index
				});
			});
			
			// 부여된 id 값을 이용하여 <p> 값을 </p> 추출 : text()
			$('#btn').click(function() {
				alert($('#para_0').text());
			});

        });
    </script>

</head>

<body>

    <p>C#</p>
    <p>ASP.NET</p>
    <p>Silverlight</p>
    <input type="button" id="btn" value="동적으로 생성된 id로 개체 접근" />

</body>

</html>




 

'WEB > jQuery' 카테고리의 다른 글

[jQuery] bind & unbind  (0) 2021.06.07
[jQuery] 다양한 Selector 이용  (0) 2021.06.07
[jQuery] form 태그 내 입력 값, 선택 값 제어  (0) 2021.06.07
[jQuery] text() & html()  (0) 2021.06.07
[jQuery] removeAttr()  (0) 2021.06.07
Comments