【问题标题】:Truncate number of li's in a list if more than a certain number如果超过一定数量,则截断列表中的 li 数量
【发布时间】:2013-04-28 18:48:27
【问题描述】:

我想实现以下目标:

如果给定的 ul 中的 li 超过 12 个,则将最后一个替换为“...”并隐藏第 12 个之后出现的任何内容。

谁能指点我的路?

【问题讨论】:

  • 你试过什么?您需要展示您的努力和代码,以便我们为您提供适当的帮助

标签: jquery truncate


【解决方案1】:

你可以简单地使用 jQuery .slice()

$('ul').html($('ul li').slice(0,12)).append("..");

看到这个fiddle

【讨论】:

    【解决方案2】:

    这里是工作小提琴: http://jsfiddle.net/acturbo/w3yep/7/

    示例 html:

    <ul id="mylist">
        <li>1 </li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5 last one to see</li>
        <li>6 will be truncated</li>
        <li>7 will be truncated</li>
        <li>8 will be truncated </li>
    </ul>  
    

    jquery:

    $(document).ready(function () {
       var maxToShow = 5;
    
        $("#mylist li").each( function(i, e){
            // truncate all li elements after the 5th
            if ( i >= maxToShow){
                // $(e).remove(); // remove it
                $(e).hide(); // or hide it
            }
        });
    
    });
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $('#myList > li:eq(11)').nextAll().hide().end().after('<li>...</li>'); 
      

      FIDDLE

      请注意,eq() 方法中提供的索引是从零开始的,并且是指元素在 jQuery 对象中的位置,而不是在 DOM 树中。因此,eq(11) 在这里表示第 12 项。

      【讨论】:

        【解决方案4】:

        LIVE DEMO

        <ul data-truncate="12">
        

        jQuery:

        $('[data-truncate]').each(function(){
          var n = $(this).data('truncate') -1;
          $('li', this).eq( n ).nextAll().hide().last().after('<li>...</li>');  
        });
        

        【讨论】:

          猜你喜欢
          • 2018-12-22
          • 1970-01-01
          • 2010-11-19
          • 2011-04-16
          • 2011-02-27
          • 1970-01-01
          • 2015-05-28
          • 1970-01-01
          • 2018-07-03
          相关资源
          最近更新 更多