본문 바로가기

Skills/Web

JQuery Basic 12강 - each()

SMALL

이번에는 each() 메소드를 사용해보도록 하겠습니다.

 

자바에는 for, while 반복문이 있습니다. 자바스크립 또 한 for 문이있습니다. 그러나 jQuery에는 새로운것이있습니다. 바로 each() 입니다. each() 메소드의 parmeter 즉 인자 값으로 callback 메소드를 줄일 수 있습니다.

 

시작하겠습니다. 준비된 소스를 보시죠.


 

 <!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<style type="text/css">

 

</style>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script type="text/javascript">

$(document).ready(function() {

});

</script>

</head>

<body>

 

</body>

</html>

 

 

<body>에 사용할 내용을 입력하겠습니다. 

 

 

 

 <h1> 태그에 4개의 내용을 입력하였습니다. 그리고 each를 사용해보겠습니다.

 

 

 

 

 i 라는 변수에 초기값을 0으로 설정합니다.

document에 ready로 <h1>태그에 each(forEach)로 작동시킵니다.

함수 forEach를 tis의 attr로 속성값 class 를 fromjQuery + i 로 부여합니다.

i 변수에 +1 을 더합니다.

 

 

인자 값이 몇개인가에 따라 2가지로 사용할수 있다. 하나의 인자만 있을 경우 그 인자에 해당하는 값을 가져오는거고,

두 개의 인자가 있을 경우 그 속상값을 요소에 부여하는 것이다. (ex, {속성명 : 값} )


.attr(attributeName) 이렇게 사용할 경우 첫 번째 요소의 attributeName에 해당하는 속성 값을 반환하는데, 만약 속성값을 가져오지 못하면 undefinded를 반환한다.


 

 

 

<style>를 적용합니다.

 

 

 

 

 

결과.



 

 

 <!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<style type="text/css">

.fromjQuery0 { color:Orange; }

.fromjQuery1 { color:Red; }

.fromjQuery2 { color:Blue; }

.fromjQuery3 { color:Brown; }

.fromjQuery4 { color:Pink; }

</style>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script type="text/javascript">

var i = 0;

$(document).ready(function() {

$("h1").each(forEach);

});

function forEach(){

$(this).attr({"class": "fromjQuery" + i});

i++;

}

</script>

</head>

<body>

<h1>RintIanTta</h1>

<h1>RantIanTta</h1>

<h1>IanKelRaucTta</h1>

<h1>HaraRect</h1>

<h1>VhenSiliate</h1>

</body>

</html>


 

LIST