简体   繁体   English

jquery - 在UL中仅显示15个列表项

[英]jquery - Display only 15 list items in a UL

I have a list that is generated by WordPress and I there is no way to limit how many tags to display through the function it self. 我有一个由WordPress生成的列表,我没有办法限制通过它自己的功能显示多少标签。

With jQuery I decided to do this to display only the first 15: 使用jQuery我决定这样做只显示前15个:

$j(function(){
    if( $j('#popular-tags').length > 0 ){
        var displayAmt = 15;

        var list = $j(this).find('ul');
        for(var i=1; i <= displayAmt; i++ ){
            ....
        }
    }
});

I'm a bit lost on how to iterate through each list item. 我对如何遍历每个列表项有点迷失。 But i have a class called .not-display that I want to add to the respective list item. 但我有一个名为.not-display的类,我想添加到相应的列表项。 I also wasn't sure if I need to use the .each() function that jQuery provides. 我也不确定是否需要使用jQuery提供的.each()函数。

Can someone enlighten me? 有人可以开导我吗?

You'll find that most of the time, a loop is not necessary with jQuery: 你会发现大多数时候,jQuery不需要循环:

var displayAmt = 15;
$j('#popular-tags li').slice(displayAmt).hide();

This code finds all the li elements within the #popular-tags div, uses slice() to get every element after the 15th element, and calls hide() on them all. 此代码查找#popular-tags div中的所有li元素,使用slice()获取第15个元素之后的每个元素,并对它们全部调用hide() You can also choose to call remove() instead if you wish. 如果您愿意,也可以选择调用remove()

我建议使用lt选择器 ,它采用从零开始的索引:

$("ul > li:lt(15)").show();

Taking the opposite of Karims answer using the gt selector 与Karims相反,使用gt选择器回答

$("ul > li:gt(14)").hide();  

or if you want to apply your class: 或者如果你想申请你的课程:

$("ul > li:gt(14)").addClass("not-display");

You can try the Show First N Items jQuery Plugin . 你可以试试Show First N Items jQuery插件 All you need to write is this: 所有你需要写的是:

<ul class="show-first" data-show-first-count="15"  data-show-first-has-control="false">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
    <li>13</li>
    <li>14</li>
    <li>15</li>
    <li>16</li>
    <li>17</li>
    <li>18</li>
    <li>19</li>
    <li>20</li>
</ul>

It will automatically convert to this: 它会自动转换为:

<ul class="show-first" data-show-first-count="15" data-show-first-has-control="false">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
    <li>13</li>
    <li>14</li>
    <li>15</li>
    <li style="display: none;">16</li>
    <li style="display: none;">17</li>
    <li style="display: none;">18</li>
    <li style="display: none;">19</li>
    <li style="display: none;">20</li>
</ul>

Fyi, I contributed code to this plugin. Fyi,我为这个插件贡献了代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM