How might I use jQuery to show the first 8 elements?
I have a list of items (<li>
), som开发者_如何转开发ething like 50 of them, and I want to show only the first 8 items... How can I do that?
$("li:lt(8)").show();
This selects the first 8 li elements. The :li selects elements with an index less than the chosen number.
$('li:gt(7)').hide();
You use 7 because it's a zero based index.
Use the less-than selector to select all list items with indexes less than 8 (index 8 is the ninth list item). Then show them:
$("#mylist li:lt(8)").show();
(assumes your list - ol
or ul
- has an id
of mylist
; adjust accordingly)
You might need to do this in two steps, if some list items are initially visible:
$("#mylist li") // select all list items
.hide() // hide them
.filter("li:lt(8)") // now select just the first eight
.show(); // ...and show them.
(actually, this is over-kill unless some items are shown and some are hidden - if you know for a fact that all items are initially visible, you can use the greater-than selector to simply hide items with index 8 and above - as Corey demonstrates)
$("li:lt(8)") the :lt selects all li elements with index less than 8
精彩评论