4

I am trying to select <li> in groups of 3, currently I am using :gt and :lt like this

 $('.events_list li:lt(7):gt(3)').css('display', 'block');

This is ok but seems like there may be a better way. I just want to click a button and select the next 3 <li>.

4

4 回答 4

4

Try

var triplet = 0;

$('button').click(function(){
    $('.events_list li')
        .hide() // hide the ones that are visible
        .filter(function(i){
            return i >= triplet*3 && i < (triplet+1)*3; // filter the next 3
        })
        .show(); // and show them

    triplet++;
});

demo at http://jsfiddle.net/PyEhU/

于 2012-10-04T10:16:07.597 回答
0

you can try also nextUntil:

$('.events_list li:eq(3)').nextUntil('.events_list li:eq(7)').css('display', 'block');
于 2012-10-04T10:13:39.953 回答
0
jQuery("ul li").filter(function(index,el){return index>3 && index<7}).css('display', 'block');

Try this.

于 2012-10-04T10:16:34.643 回答
0

Gaby's answer worked well for me (and I would have upvoted it if I could), but my use case required a loop, and the one issue with $.filter is that it goes over all the elements in every loop pass. So I used slice instead, which allows you to select elements out of a set. It also makes the code slightly simpler. As an added bonus, I moved the selector out of the function, as I assume the list itself does not change and therefore there's no need to select it again and again.

This is my version, based on Gaby's:

var triplet = 0;
var $elements = $('.events_list li');

$('button').click(function(){
    $elements
        .hide() // hide the ones that are visible
        .slice( triplet*3, (triplet+1)*3)
        .show(); // and show them

    triplet++;
});

Demo at http://jsfiddle.net/sf3N9/

于 2014-03-24T15:16:06.850 回答