jQuery each 함수를 이용하여 선택된 요소만큼 반복하는 each() 함수를 알아보겠습니다.

1. each()

선택된 요소만큼 반복 작업을 진행하는 함수 입니다.


게시판에서 자주 쓰는 전체 선택 전체 해제를 예제로 each함수를 알아보겠습니다.

<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>
<div><span class="chk">체크박스</span></div>

<button id="check">전체 선택</button><button id="uncheck">전체 해제</button>


- jQuery

$(document).ready(function () {
	$('#check').off('click').on('click', function() {
    	$('.chk').each(function () {
        	$(this).addClass('active');
        });
    });
    
    $('#uncheck').off('click').on('click', function() {
    	$('.chk').each(function () {
        	$(this).removeClass('active');
        });
    });
});


전체 선택 버튼이 클릭됐을 때 each함수를 이용하여 chk 클래스를 가진DOM에 active 클래스를 추가하고

전체 해제 버튼 클릭시에 chk클래스를 가진 DOM에 active 클래스를 삭제합니다.


 : 이동



+ Recent posts