jQuery show first X elements with More and Less links

馋奶兔 提交于 2019-12-22 04:09:14

问题


I am trying to find a jQuery solution to show the first 3 items on each menu in a left-hand navigation filter with a 'Show more' and 'Show less' link enabling users to expand the list.

I have searched for a solution but most expand/collapse scripts completley hide the layer whilst others show an Expand (Show more) link but do not toggle to show a Collapse (Show less) link.

My menus are coded as follows.

<div id="menu1">
<ul class="term-list">
<li class="term-item ">Item 1</li>
<li class="term-item ">Item 2</li>
<li class="term-item ">Item 3</li>
<li class="term-item ">Item 4</li>
</ul>
</div>
<div id="menu2">
<ul class="term-list">
<li class="term-item ">Item 1</li>
<li class="term-item ">Item 2</li>
<li class="term-item ">Item 3</li>
<li class="term-item ">Item 4</li>
</ul>
</div>

回答1:


jsBin demo

Here is just a basic example:

$('ul.term-list').each(function(){

  var LiN = $(this).find('li').length;

  if( LiN > 3){    
    $('li', this).eq(2).nextAll().hide().addClass('toggleable');
    $(this).append('<li class="more">More...</li>');    
  }

});


$('ul.term-list').on('click','.more', function(){

  if( $(this).hasClass('less') ){    
    $(this).text('More...').removeClass('less');    
  }else{
    $(this).text('Less...').addClass('less'); 
  }

  $(this).siblings('li.toggleable').slideToggle();

}); 

Or a more compact version.




回答2:


DEMO: http://jsfiddle.net/DQKyT/

$(function(){
    /* add button, hide extra items*/      
    $('.term-list').each(function() {
        var $list = $(this);
        $list.before('<button class="more_less">More</button>')
       $list.find('.term-item:gt(2)').hide();
    });

    /* button click handler*/
    $('.more_less').click(function() {
        var $btn = $(this)
        $btn.next().find('.term-item:gt(2)').slideToggle();    
        $btn.text($btn.text() == 'More' ? 'Less' : 'More');   
    });
})


来源:https://stackoverflow.com/questions/11073100/jquery-show-first-x-elements-with-more-and-less-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!