2013-12-15 3 views
2

지난 몇 시간 동안 시행 착오를 거친 후 jQuery의 기본을 익히는 것이 좋습니다. 누군가가 간단한 대답 일 가능성이있는 것을 도와 줄 수 있습니까?아코디언 활성 아이템을 클릭 할 수있게 만드는 방법

나는 페이지에 this 아코디언을 붙이고 있지만 활성 패널을 클릭하여 닫을 수있게하고 싶습니다. 가능한 한 간단하게 할 수 있습니까?

jQuery('.accordion > dt').on('click', function() { 
     //this clicked panel 
     var $this = $(this), 
      $target = $this.next(); 

     //slide up any open panels and remove active class 
     $this.parent().children('dd').not($target).slideUp(); //Slide Up everything but the target one 

     //remove any active class 
     jQuery('.accordion > dt').removeClass('accordion-active'); 
     //add active class 
     $this.addClass('accordion-active'); 
     //slide down target panel 
     $target.addClass('active').slideToggle(); 

    return false; 
    }); 

Demo

그리고 실제로 당신은이를 단순화 할 수 있습니다 :

(function($) { 

    //Hide all panels 
    var allPanels = $('.accordion > dd').hide(); 

    //Show first panel 
    $('.accordion > dd:first-of-type').show(); 

    //Add active class to first panel 
    $('.accordion > dt:first-of-type').addClass('accordion-active'); 

    //Handle click function 
    jQuery('.accordion > dt').on('click', function() { 

    //this clicked panel 
    $this = $(this); 

    //the target panel content 
    $target = $this.next(); 

    //Only toggle non-displayed 
    if(!$this.hasClass('accordion-active')){ 

     //slide up any open panels and remove active class 
     $this.parent().children('dd').slideUp(); 

     //remove any active class 
     jQuery('.accordion > dt').removeClass('accordion-active'); 

     //add active class 
     $this.addClass('accordion-active'); 

     //slide down target panel 
     $target.addClass('active').slideDown(); 

    } 

    return false; 
    }); 

})(jQuery); 

답변

2
시도

jQuery('.accordion > dt').on('click', function() { 
     var $this = $(this) , 
      $target = $this.next(); 

     $('.accordion > dt.accordion-active').not($this.toggleClass('accordion-active')).removeClass('accordion-active'); 

     $this.siblings('dd').not($target.addClass('active').slideToggle()).slideUp(); 

     return false; 
    }); 

Demo

+1

어쩌면 틀렸 겠지만 ... .parent(). children ('dd')'.siblings ('dd')'를 말하는 것보다 길습니까? 나는 그것을 자주 사용하지 않기 때문에 나는 실제로 호기심이있다 – Deryck

+0

Brillant. PSL과 Deryck에게 감사드립니다. 매력처럼 일했습니다! – dotwongdotcom

+0

@dotwongdotcom 두 번째 버전도 환영합니다. – PSL

관련 문제