jQuery count amount of divs on a page and hide? [c

2019-09-21 11:22发布

问题:

I'm displaying an amount of divs on a page that can be anywhere from 1-50, all will be generated and loaded into the HTML via PHP, but I want to only display 9 initially and then load an additional 9 on a button click until all are loaded.

   var alldivs = $('.preview-container').hide();

$('button').on('click', function(){
    var turn = alldivs.splice(0, 9);
    if (turn.length) {
        console.log(turn);
        turn.fadeIn();
    }
});

回答1:

Your question is very vague. For a better reference, you need to post your current code, what precisely you need to do and what you have searched so far. So it can help you to receive a better answer. But most likely you are looking for something like this:

$('li').click(function() {
    var which = $(this).index();
    $('div').find('div').hide().eq(which).show();
});


回答2:

This is the shortest code I can think to do this:

var alldivs = $('div'); // select the elements you want to show here

$('button').on('click', function(){
    var turn = alldivs.splice(0, 9);
    if (turn.length) {
        turn.fadeIn();
    }
});

As the jQuery-selector returns an array with the matched elements you can combine that with the Array splice method to do what you want.

Basically alldivs.splice(0, 9) remove nine items starting at position zero from alldivs and returns the removed items.

Hope it helps.