2013-10-13 81 views
0

我已拼湊在一起以下切換顯示第一個段落更多botton作爲第一段內的跨度。當點擊更多時,其他段落顯示,更多的按鈕被隱藏,但是當點擊更少的按鈕時,我需要更多的按鈕返回..你能幫忙嗎?JQuery更多/更少切換

<script> 
    $('div#introduction').each(function(){ 
    var NODES = $(this).find('p').length; 
    if(NODES>0){ 
     $(this).find('p:first').addClass('first'); 
     $(this).find('p:last').addClass('last'); 
     $('#introduction p.first').append('&nbsp;<span class="more"><a class="toggle">More</a></span>'); 
     $('#introduction p.last').append('&nbsp;<span class="less"><a class="toggle">less</a></span>'); 
     $('#introduction p').hide().slice(0,1).addClass('fixed').show(); 
     $('.toggle').click(function(){ 
     $(".more").hide(); 
     $('p:not(.toggle,.fixed)').toggle(); 
     $(this).text(function(_, ML){ 
     return ML === 'Less' ? 'More' : 'Less'; 
     }); 
     }); 
    } 
    }); 
    </script> 

提前

斯圖

回答

3

非常感謝那豈不是足以取代這個:

$(".more").hide(); 

與此:

$(".more").toggle(); 

...然後刪除該代碼改變文本,以便您單擊處理結束這樣的:

$('.toggle').click(function(){ 
    $(".more").toggle(); 
    $('p:not(.toggle,.fixed)').toggle(); 
    }); 

演示:http://jsfiddle.net/dXJrr/

從那以後,所有你正在做的是切換的東西,你可以你的點擊處理程序減少到一個行:

 $('.more, p:not(.toggle,.fixed)').toggle(); 

...但你可以得到這樣一個漂亮的效果:

 $('.more').toggle(); 
    $('p:not(.toggle,.fixed)').slideToggle(); 

演示:http://jsfiddle.net/dXJrr/2/

+0

+1。更好的方法。我認爲文本切換部分(在問題中存在)不是必需的,因爲第一個和最後一個存在一個「a」。 – Harry

+0

謝謝@哈里。是的,如果該元素不是隱藏的,則更改文本的代碼纔有意義。 – nnnnnn

1

如果我的理解是正確的,下面是你需要的。

$('div#introduction').each(function() { 
     var NODES = $(this).find('p').length; 
     if (NODES > 0) { 
      $(this).find('p:first').addClass('first'); 
      $(this).find('p:last').addClass('last'); 
      $('#introduction p.first').append('&nbsp;<span class="more"><a class="toggle">More</a></span>'); 
      $('#introduction p.last').append('&nbsp;<span class="less"><a class="toggle">Less</a></span>'); 
      $('#introduction p').hide().slice(0, 1).addClass('fixed').show(); 
      $('.more').click(function() { 
       $('p:not(.toggle,.fixed)').toggle(); 
       $(".less").show(); 
       $(".more").hide(); 
      }); 
      $('.less').click(function() { 
       $('p:not(.toggle,.fixed)').toggle(); 
       $(".more").show(); 
       $(".less").hide(); 
      }); 
     } 
    }); 

Demo Fiddle

+1

謝謝哈利,我花了好幾個小時擺弄這個。 – Stuart

+0

@Stuart:總是很高興能成爲幫手隊友:)我剛纔說你應該接受nnnnnn的解決方案,因爲那是更好的解決方案。很高興看到你已經做到了:) – Harry