2013-08-05 87 views
0

我想用自己的手勢來使用jQuery建立一個手風琴。這很簡單,但我無法正確理解。被我的jquery簡單的手風琴卡住了

這是我的HTML

<div id="three"> 
    <dt><a href="#">click one</a></dt> 
    <dd>content one</dd> 
    <dt><a href="#">click two</a></dt> 
    <dd>content two</dd> 
    <dt><a href="#">click three</a></dt> 
    <dd>content three</dd> 
</div> 

這是我的腳本

$('dd').hide(); 
$('a').on('click', function(){ 
    $(this).parent().next('dd').toggle('slow', function() { 
    }); 
$(this).parent().siblings('dd').hide(); 
}) 

點擊一個dt a時,會切換dd內容,但我想關閉開放的另一dd爲好。

+0

而不是切換你想要顯示的dd。也許你會更好地隱藏所有的dt。然後顯示'this.next('dd')' – TCHdvlp

回答

1

我建議給予元素持有根據一類,這樣就可以很容易地找到手風琴的「根」:

<div id="three" class="accordion"> 

然後你就可以很容易地找到所有dd元素在裏頭隱藏所有的人,但被點擊的一個:

$('a').on('click', function(){ 
    var $dd = $(this).parent().next('dd'); 
    // hide all others 
    $(this).closest('.accordion').find('dd').not($dd).hide(); 
    $dd.toggle('slow'); 
}); 

一般來說,如果你使用類比使用元素更多(即.accordion-header.accordion-content或類似的東西),並且使用「相對」DOM遍歷(.closest)而不是直接遍歷($(this).parent()),可以使您的手風琴實現更加靈活。

0

onclick你只是hide all之前toggling.

$('dd').hide(); 

$('a').on('click', function(){ 
    $('dd').hide(); 
    $(this).parent().next('dd').toggle('slow', function() { 
    }); 

}) 

Demo Fiddle

+1

點擊一個打開的面板現在不會關閉它。 –

1

上點擊隱藏

$('dd').hide(); 
$('a').on('click', function(){ $(this).parent().next('dd').toggle('slow').siblings('dd').hide('slow'); 
}) 

DEMO

0

HI嘗試這樣,

$(function() { 
$("#three").accordion(); 
}); 

可以使用Jquery Ui

http://jqueryui.com/accordion/

+0

'.accordion'從哪裏來?這不是一個jQuery方法:http://api.jquery.com/?s=accordion。 –

+0

@felix kling jquery provode'.accordion' http:// jqueryui。com/accordion/ – Jaimin

+0

這是jQuery UI,而不是jQuery。 OP沒有提到他使用jQuery UI,所以如果你的答案取決於它,那麼你應該至少在你的答案中解釋這一點。無論如何,它不是一個有用的答案IMO,因爲OP想知道他如何用他的代碼實現效果。 –

0

與下面的代碼嘗試使用accordion

$('a').on('click', function(){ 
    $(this).parent().parent().find('dd').stop(true,true).slideUp(); 
    $(this).parent().next('dd').stop(true,true).slideDown();  
}); 
0

您可以使用JQuery UI Accordionthis鏈接。並用它喜歡:

$(function() { 
    $("#accordion").accordion(); 
}); 

在此結構:

<div id="accordion"> 
    <h3>click one</h3> 
    <div><p>content one</p></div> 
    <h3>click two</h3> 
    <div><p>content two</p></div> 
    <h3>click three</h3> 
    <div><p>content three</p></div> 
</div> 

見例如there