开发者

jquery - Display only 15 list items in a UL

开发者 https://www.devze.com 2023-02-20 05:02 出处:网络
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.

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.

With jQuery I decided to do this to display only the first 15:

$j(function(){
    if( $j('#popular-tags').len开发者_开发问答gth > 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. I also wasn't sure if I need to use the .each() function that jQuery provides.

Can someone enlighten me?


You'll find that most of the time, a loop is not necessary with 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. You can also choose to call remove() instead if you wish.


I would suggest using the lt selector, which takes a zero-based index:

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


Taking the opposite of Karims answer using the gt selector

$("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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消