자바스크립트 질문이 있습니다. 채택완료
Copy
1
2
3
4
5
6
1
2
3
4
5
6
버튼 클릭시 하단 컨텐츠가 바뀌는 방식인데
자바스크립트를 쌩 노가다 처럼 입력하고 있는데 혹시 간편한 방법이 없나 궁금해서 질문드립니다.
현재는 아래와 같이 작업을 하고 있습니다
Copy
$(function(){
$(".type_btn_wrap .btn01").click(function(){
$(".type_btn_wrap .btn01").addClass("active");
$(".type_btn_wrap .btn02").removeClass("active");
$(".type_btn_wrap .btn03").removeClass("active");
$(".type_btn_wrap .btn04").removeClass("active");
$(".type_btn_wrap .btn05").removeClass("active");
$(".type_btn_wrap .btn06").removeClass("active");
$(".type_wrap .type01").addClass("active");
$(".type_wrap .type02").removeClass("active");
$(".type_wrap .type03").removeClass("active");
$(".type_wrap .type04").removeClass("active");
$(".type_wrap .type05").removeClass("active");
$(".type_wrap .type06").removeClass("active");
});
});
$(function(){
$(".type_btn_wrap .btn02").click(function(){
$(".type_btn_wrap .btn02").addClass("active");
$(".type_btn_wrap .btn01").removeClass("active");
$(".type_btn_wrap .btn03").removeClass("active");
$(".type_btn_wrap .btn04").removeClass("active");
$(".type_btn_wrap .btn05").removeClass("active");
$(".type_btn_wrap .btn06").removeClass("active");
$(".type_wrap .type02").addClass("active");
$(".type_wrap .type01").removeClass("active");
$(".type_wrap .type03").removeClass("active");
$(".type_wrap .type04").removeClass("active");
$(".type_wrap .type05").removeClass("active");
$(".type_wrap .type06").removeClass("active");
});
});
.
.
.
.
.6번 까지 반복...
답변 1개
채택된 답변
+20 포인트
10개월 전
현재 구현 방식은 각 버튼마다 별도의 클릭 이벤트를 등록해 클래스 토글을 수행하고 있어
코드의 중복이 많고 유지보수 측면에서 비효율적입니다.
이를 개선한, 버튼과 콘텐츠를 인덱스 기반으로 접근하는 방법이 있습니다.
Copy
이와 같이 작성하면 버튼의 수가 늘어나더라도
$(function(){
$('.type_btn_wrap li').click(function(){
var index = $(this).index(); // 클릭한 버튼의 인덱스 가져오기
// 모든 버튼과 콘텐츠에서 active 클래스 제거
$('.type_btn_wrap li').removeClass('active');
$('.type_wrap').removeClass('active');
// 해당 버튼과 콘텐츠에 active 클래스 추가
$(this).addClass('active');
$('.type_wrap').eq(index).addClass('active');
});
});
코드 변경 없이 자동으로 대응할 수 있어 유지보수와 가독성이 크게 향상됩니다.
로그인 후 평가할 수 있습니다
답변에 대한 댓글 2개
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인