Onclick show next divs

前端 未结 3 906
無奈伤痛
無奈伤痛 2021-01-29 08:49

I have 1000 divs and 20 of them are visible and remaining are hidden.

In the onClick jquery event, I want the next 20 divs to become visible and so on.

3条回答
  •  滥情空心
    2021-01-29 09:35

    I'd suggest something akin to the following, though I'd strongly recommend making it into a function, or plugin:

    var perSlice = 20; // how many to show on each 'page'
    
    // hides all but the first 'page' of the matched elements
    $('#wrap > div').hide().slice(0, perSlice).show();
    
    $('a').click(
        function(e) {
                // reference to the elements being 'paged'
            var divs = $('#wrap div'),
                // the first of the visible 'paged' elements
                firstVisible = divs.filter(':visible:first'),
                // the index of the first visible 'paged' elements
                firstVisibleIndex = firstVisible.index('#wrap div'),
                lastVisible = divs.filter(':visible:last'),
                lastVisibleIndex = lastVisible.index('#wrap div'),
                // the index of the first of the 'paged' elements
                firstIndex = divs.filter(':first').index('#wrap div'),
                lastIndex = divs.filter(':last').index('#wrap div');
    
            // if you've clicked the a element with id="prev"
            if (this.id == 'prev') {
                // prevents the default action of the link
                e.preventDefault();
                // if the index of the first visible element is the same as the
                // index of the first element
                if (firstVisibleIndex == firstIndex) {
                    // don't do anything, and exit
                    return false;
                }
                else {
                    // otherwise, hide all the paged elements
                    divs.hide();
                    // and then take a selection of those paged elements, and show them
                    divs.slice((firstVisibleIndex) - perSlice, firstVisibleIndex).show();
                }
            }
            else if (this.id == 'next') {
                e.preventDefault();
                if (lastVisibleIndex == lastIndex) {
                    return false;
                }
                else {
                    divs.hide();
                    divs.slice((lastVisibleIndex + 1), (lastVisibleIndex + 1) + perSlice).show();
                }
            }
        });​
    

    JS Fiddle demo.

    References:

    • event.prevendDefault().
    • filter().
    • :first selector.
    • hide().
    • index().
    • :last selector.
    • slice().
    • show().
    • :visible selector.

提交回复
热议问题