2010-05-18 91 views
1

如圖所示:http://www.learningjquery.com/2007/03/accordion-madness。但我需要幫助來編輯它,以便它適用於我的情況。我怎樣才能使一個div擴大點擊一次只打開一個?

樣本HTML

<div class="row even"> 
<div class="info"> 
    <div class="class">CK1</div> 
    <div class="teacher_chinese">老師</div> 
    <div class="teacher_english">Teacher Name</div> 
    <div class="assistant_chinese">助教</div> 
    <div class="assistant_english">Assistant Name</div> 
    <div class="room">Room 00</div> 
    <div class="book"></div> 
</div> 
<div class="chapters"> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=1"><span class="chapter">一</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=2"><span class="chapter">二</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=3"><span class="chapter">三</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=4"><span class="chapter">四</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=5"><span class="chapter">五</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=6"><span class="chapter">六</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=7"><span class="chapter">七</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=8"><span class="chapter">八</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=9"><span class="chapter">九</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=10"><span class="chapter">十</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=11"><span class="chapter">十一</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=12"><span class="chapter">十二</span></a> 
    <a href="../../curriculum/cantonese/textbook.php?cls=C1&amp;ch=13"><span class="chapter">十三</span></a> 
</div> 
</div> 

JQUERY [正在進行的工作]

$(document).ready(function() { 
$('div#table_cantonese .chapters').hide(); 
$('div#table_cantonese .book').click(function() { 
    var $nextDiv = $(this).next(); 
    var $visibleSiblings = $nextDiv.siblings('div:visible'); 
    if ($visibleSiblings.length) { 
    $visibleSiblings.slideUp('fast', function() { 
     $nextDiv.slideToggle('fast'); 
    }); 
    } else { 
    $nextDiv.slideToggle('fast'); 
    } 
}); 
}); 

所以,當上div.book最終用戶點擊,div.chapters將擴大。一次只顯示一個div.chapters。所以如果一個div.chapters已經打開,那麼它會在用戶點擊動畫之前先關閉開放的。

回答

1

從概念上講,有一些明顯的方法可以實現這一點。

  1. 你可以嘗試保持一個句柄 應在 這個非常時刻打開的股利。當一個新的div被選中時,首先隱藏打開的div, 然後打開新的div,並將 當前打開的句柄分配給現在的 打開的div。
  2. 使它成爲這樣,當你點擊 任何,它只是關閉所有div沒有 事情是什麼,然後打開只是被選中的div 。
  3. ...

的訣竅是,僅僅這些技術對所有通過應用你的JavaScript到所有選中時應該表現的div的父變得簡單。

1

使用全局變量來存儲先前打開的DIV。然後,當打開一個新的DIV時,關閉先前打開的一個。

var prev=false; 

//... 

if(prev!==false) 
    // close prev 
prev = new_div; 
+0

如果可以避免,則不應創建全局變量。我會用'(function(){var prev = false; $(document).ready(/ *需要prev * /的東西);})()' – 2010-05-18 05:08:22

相關問題