2014-01-13 32 views
1

我在頁面上有四個「.content」部分。我想要切換每個部分,但還要顯示所有部分以顯示所有「.content」。當我嘗試添加一個全部顯示按鈕時,切換將停止工作。仍然習慣jQuery,任何幫助將不勝感激!顯示所有部分在jQuery中切換

這裏是HTML的結構:

<div class="row add-top"> 
     <div class="span4"> 

     <p class="expand"><a href="#">Show All</a></p> 
      <p class="contract"><a href="#">Hide All</a></p> 


    <p class="heading"><strong>Week 01 - Welcome!</strong></p><!-- WEEK --> 
    <section class="content"> 

     <p></p> 
    </section> 
    </div> 


$(document).ready(function() { 
    $(".content").hide(); 
    //toggle the componenet with class msg_body 
    $(".heading").click(function() { 
     $(this).next(".content").slideToggle(500); 
     $(".content").hide(); 
     //toggle the componenet with class msg_body 
     $(".expand").click(function() { 
      $(this).next(".content").slideToggle(500); 
      $(".content").hide(); 
      //toggle the componenet with class msg_body 
      $(".contract").click(function() { 
       $(this).next(".content").slideToggle(500); 
      }); 
     }) 
    }); 
} 
+0

可以分享你的HTML樣本 –

+0

什麼'expand'和'contract'元素 –

+0

'expand'和'contract'將顯示所有四個內容部分一次 – user3188960

回答

0

嘗試

$(document).ready(function() { 
    var $contents = $(".content").hide(); 
    $(".heading").click(function() { 
     var $next = $(this).next(".content").stop(true, true).slideToggle(500); 
     $contents.not($next).hide(); 
    }); 
    $(".expand").click(function() { 
     $contents.stop(true, true).slideDown() 
    }) 
    $(".contract").click(function() { 
     $contents.stop(true, true).slideUp() 
    }); 
}) 

演示:Fiddle

+0

我認爲'var $ contents = $(「。content」)。hide();'應該是'var $ contents = $(「。content」);' –

+0

@RohanKumar OP最初隱藏內容元素...所以它應該沒問題 –

+0

我不是在說'隱藏元素',我只是想知道,th在使用'hide()'後可以在'selector'賦值。 –

0

嘗試將所有click events結合起來,因爲這些都working same和到位的slideToggle()使用slideDown(),也不要使用next()使用$('.content') selectortoggle一樣,

$(function(){ 
    $(".content").hide(); 
    //toggle the componenet with class msg_body 
    $(".heading, .expand, .contract").click(function() { 
     $(".content").hide().slideDown(500); 
    }); 
}); 

Demo

如果你有multiple-content然後使用closest()試試這個,

$(function(){ 
    $(".content").hide(); 
    //toggle the componenet with class msg_body 
    $(".heading, .expand, .contract").click(function() { 
     $(".content").hide(); 

     // let row is parent for every div containnig heading, expan, contract 
     $(this).closest('.row').find(".content").slideDown(500); 
    }); 
});