Jquery,隐藏和显示第n项后的列表项

说我有一个无序列表,如下所示:

  • One
  • Two
  • Three
  • Four
  • Five

我如何使用JQuery隐藏最后2个列表项并在那里有一个“显示更多”链接,所以当点击时,最后2个列表项会出现?

 
  • One
  • Two
  • Three
  • Four
  • Five
  • Show More

请尝试以下代码示例:

 $('ul li:gt(3)').hide(); $('.show_button').click(function() { $('ul li:gt(3)').show(); }); 

为了好玩,这里有一个迂回的方式在一个链中做到这一点:

 $('ul') .find('li:gt(3)') .hide() .end() .append( $('
  • Show More...
  • ').click( function(){ $(this).siblings(':hidden').show().end().remove(); }) );

    我只想显示“显示/隐藏”,如果大于最大值,所以我这样做,跟随肯:

     $('ul').each(function(){ var max = 6 if ($(this).find("li").length > max) { $(this) .find('li:gt('+max+')') .hide() .end() .append( $('
  • More...
  • ').click( function(){ $(this).siblings(':hidden').show().end().remove(); }) ); } });

    它会更像这样。 您必须隐藏大于2的子项,因为Three被索引为2.此外,如果您想将Show More放在LI标记中,则需要在选择器中包含:not(:last-child) 。 像这样:

        

    在Ken和Cloud之后,我添加了“更多”按钮的规定,转到“更少”并切换相关的列表项。

     $('.nav_accordian').each(function(){ var max = 6 if ($(this).find('li').length > max) { $(this).find('li:gt('+max+')').hide().end().append('
  • (see more)
  • '); $('.sub_accordian').click( function(){ $(this).siblings(':gt('+max+')').toggle(); if ( $('.show_more').length ) { $(this).html('(see less)'); } else { $(this).html('(see more)'); }; }); }; });

    您可以尝试Show First N Items jQuery插件 。 所有你需要写的是:

     
    • One
    • Two
    • Three
    • Four
    • Five

    它会自动转换为:

      

    单击“显示更多”后,它将转换为:

      

    Fyi,我为这个插件贡献了代码。

    我假设您根据示例代码开始使用UL。

    我会发现UL并隐藏项目大于您最初要显示的最后一项的索引。 然后我会添加一个新项目作为显示其余部分的钩子。 最后,由于不再需要,我会隐藏节目更多选项。

    请参阅以下内容:

     $('ul li:gt(3)') .hide() .parent() .append('
  • Show more
  • ');