简体   繁体   中英

jQuery pagination with dynamic pagination and next and previous buttons?

I am trying to create a pagination using jQuery. the content of the pagination is generated via PHP so they are dynamic.

I have put up a simple jQuery pagination together but the issue that I have with this is that I cannot come up with any solution for Next and Previous buttons and also, to create pagination (ie 1-2-3-4-5.. etc) dynamically based on the amount of content .

at the moment, I am putting the 1-2-3 etc manually in my code using <li></li>

this is my jsfiddle code:

https://jsfiddle.net/q5rgLwb8/1/

and this is my entire code:

itemperPage = 2;

showPage = function(page) {
    $(".mypro").hide();
    $(".mypro").each(function(n) {
        if (n >= itemperPage * (page - 1) && n < itemperPage * page)
            $(this).show();
    });        
}

showPage(1);

$("#pagin li a").click(function() {
    $("#pagin li a").removeClass("current");
    $(this).addClass("current");
    showPage(parseInt($(this).text())) 
});

any help would be appreciated.

Here is your fiddle edited :

initPagination = function(itemPerPage) {
    console.log(itemPerPage);
    var nbContent = $(".mypro").length;
    var nbPage = Math.ceil(nbContent/itemPerPage);
    var contentPagination = $('#pagin');
    var classLi = '';
    for(var i = 1; i <= nbPage; i++) {
        classLi = i == 1 ? 'current' : '';
        contentPagination.append('<li class="'+classLi+'"><a href="#">'+i+'</a></li>');
    }
    $("#pagin li a").click(function() {
        $("#pagin li a").removeClass("current");
        $(this).addClass("current");
        showPage(parseInt($(this).text())) 
    });
}

https://jsfiddle.net/q5rgLwb8/2/

The principle is to create you LI based on the number on div you have and the number of content you want to be display by page. Then bind your LI for the pagination to be working.

To make the "next" and "prev" Button you can use the class you add on the current page.

You can replace your items with this code (put it after showPage(1); ):

$('.mypro').each(function (index, value) {
    $('#pagin').append(
            "<li value=" 
                   + (index + 1) 
                   + "><a href='#'>" 
                   + $(this).text() 
                   + "</a></li>");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM