본문 바로가기

기타/jQuery

[jQuery] 제이쿼리 each 함수

728x90

제이쿼리에는 for문을 더욱 쉽게 구현할 수 있는 도구인 each가 있습니다.

for문은 조건식이 매우 복잡하게 들어가는데 each는 그것을 생략할 수 있기 때문에 훨씬 간결한 코드가 가능합니다.

배열, 객체, html 태그에 적용할 수 있습니다.

각각에 대해 예시를 통해 알아보도록 하죠.

 

1.array에 적용하기.

$.each(array, callback);
var a = new Array(1,2,3,4)
$.each(a,function(index,value){
    console.log(index,value)
    });

 

2.object에 적용하기.

$.each(object, callback);
var a = {
    name: 'Lee',
    gender: 'male'
}
$.each(a, function (index, value) {
    console.log(index, value) 
    });

 

3.html태그에 적용하기.

$(태그이름).each(callback);
<div id="a">
    <p id="b">1</p>
    <p id="c">2</p>
    <p id="d">3</p>
</div>
<script>
    $('p').each(function(index,value){
        console.log($(value).text())
    });
</script>

 

 

자주 사용하는 함수이니 꼭 알아두시기 바랍니다.

728x90