2012-10-21 41 views
1

我有以下代碼,用於常見問題列表。當用戶點擊按鈕時,信息向下滑動以顯示內容。然後他們可以點擊相同的按鈕關閉內容。在打開和關閉列表之間切換

因爲我在這個頁面上有多個列表,我想要的是如果一個列表是打開的,並且用戶單擊另一個列表打開它,則打開列表關閉,另一列表打開。這樣一個用戶沒有一英里長的滾動條。

這裏是我的代碼:

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