본문 바로가기

강좌/jQuery

제이쿼리(jQuery) - each() 메서드

1. each()메소드 -  요소만큼 반복해서 속성 설정 및 가져오기


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

    <head>

<meta http-equiv="content-type" content="text/html;" charset="utf-8" >

        <title> 요소만큼 반복해서 속성 설정 및 가져오기 </title>

<script src="http://code.jquery.com/jquery-1.7.2.js"></script>

<style type="text/css">

            .red{color:red;}

</style>

<script>

   $(document).ready(function (){

   //[1]index변수는 p태그의 index번호.

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

   $(this).attr({ //attr({attribute value})

    'id':"para-"+index

});

});


$('#btn').click(function(){

   alert($('#para-2').text()); //text():태그안의 값

});


});

</script>

    </head>


    <body>

   <p>첫번째</p>

   <p>두번째</p>

   <p>세번째</p>

   <p>네번째</p>

<input type="button" id="btn" value="button">

    </body>

</html>



2. for문을 each문으로 변경

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
<meta http-equiv="content-type" content="text/html;" charset="utf-8" >
        <title> 요소만큼 반복해서 속성 설정 및 가져오기 </title>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<style type="text/css">
            .red{color:red;}
</style>
<script>
   $(document).ready(function (){
var headers = $('h3');
//반복문을 써서 반복:for문보다는 jquery의 each문이 사용하기 편리
for(var i=0;i<headers.length;i++){
alert($(headers[i]).html());
}
//위의 코드를 each문으로 변경
$('h3').each(function(index){
alert($(this).html());
});
});
</script>
    </head>

    <body>
<h3>제목1</h3>
<h3>제목2</h3>
    </body>
</html>