2012-10-21 2 views
1

다음과 같은 FAQ 코드가 있습니다. 사용자가 버튼을 클릭하면 정보가 아래로 슬라이드되어 내용을 표시합니다. 그런 다음 동일한 버튼을 클릭하여 콘텐츠를 닫을 수 있습니다.열기 및 닫기 목록 간 전환

이 페이지에 여러 목록이 있는데 목록이 열려 있고 사용자가 다른 목록을 클릭하여 목록을 열면 목록이 닫히고 다른 목록이 열립니다. 그렇게하면 사용자는 마일 길이의 스크롤바가 생기지 않습니다. 여기

내 코드입니다 :

JS

$('.service').live('click',function(){ 
    $(this).parent().children().toggle(); //swaps the display:none between the two spans 
    $(this).parent().parent().find('.content').slideToggle(); //swap the display of the main content with slide action 
}); 

$('.service').click(function(e) { 
    e.preventDefault(); //Prevents link from taking them to top of page 
}); 

HTML

<div class="service-container"> 
<div class='service-title'> 
    <a href="#" class="service fancy_button"><span style="background-color: #0f071e;"><i class="icon-plus"></i> Open</span></a> 
    <a href="#" class="service fancy_button" style="display:none;"><span style="background-color: #666;"><i class="icon-minus"></i> Close</span></a> 
    </div> 
    <div class='content' style='display:none;'> 
     <p>My Content</p> 
    </div> 
</div> 

이 있다면 내가 다시 쓰는 코드를 신경 쓰지 않는다 더 나은 방법 이.

아이디어 :

screenshot

답변

2

은 주로 내가이되지 않기 때문에 당신이 live() 방법을 사용하지 않는 것이 좋을 것.

$(".service-title").on("click", ".service", function(e) { 
    $(this).siblings().andSelf().toggle() 
     .parent().siblings(".content").slideToggle(); 

    e.preventDefault(); 
}); 

DEMO :http://jsfiddle.net/bnT6Q/

, 우리는 코드를 조금 다시 수있는 다른 열 컨테이너 전류가 열릴 때 폐쇄하기 위해서는 :

대신, 다음과 같은 방법으로 방법 on()을 사용할 수있다
$(".service-title").on("click", ".service", function(e) { 
    $(".service-container") 
     .has($(".content:visible").add(this)) 
     .find(".service").toggle().end() 
     .find(".content").slideToggle(); 

    e.preventDefault(); 
});​ 

DEMO :http://jsfiddle.net/bnT6Q/1/

+0

도움과 코드 개선에 감사드립니다. 하나의 질문이지만, 현재 열려있는 상자를 닫으려면 어떻게해야합니까? 내 생각을 보여주는 스크린 샷을 추가했습니다. – L84

+0

@Lynda 계획대로 작동하지 않습니까? 내 피들 않습니다. – VisioN

+0

두 번째 열린 상자를 클릭하면 첫 번째 상자가 닫히지 않아 닫힙니다. 당신의 바이올린은 그렇게하지 않습니다. – L84