Select every nth item in jQuery?
jQuery has the handy :even and :odd selectors for selecting the even- or odd-indexed items in a set, which I'm using to clear every other item in a series of floated boxes, as f开发者_如何转开发ollows:
<div class='2up'>
<div> ... </div>
<div> ... </div>
...
<div> ... </div>
</div>
and
// Clear every 2nd block for 2-up blocks
$('.2up>div:even').css("clear", "both");
This works like a charm.
My question: Is there a straightforward way in jQuery to select every third or fourth item, so I could do the same thing with 3-up or 4-up items?
Try:
$("div:nth-child(3n+1)").css("clear", "both");
You could use the :nth-child(index/even/odd/equation) selector. http://docs.jquery.com/Selectors/nthChild#index
you can use the :nth-child(index/even/odd/equation) selector.
Example:
<div class='5up'>
<div> ... </div>
<div> ... </div>
...
<div> ... </div>
</div>
and// Clear every 5th block for 5-up blocks
$('.5up>div:nth-child(5n)').css("clear", "both");
or// Clear after every 5th block for 5-up blocks
// note: This will also clear first block.
$('.5up>div:nth-child(5n+1)').css("clear", "both");
No, not as such. The filter
function will let you do that though.
EDIT:
I stand corrected. Use the n-th child function for simplicity.
精彩评论