首页 > 代码库 > JavaScript显示分页按钮

JavaScript显示分页按钮

/** * * @param total_page    总页数 * @param current_page  当前页 * @param num           页面显示多少个分页按钮 * @returns {string} */exports.get_page_html = function(total_page,current_page,num){    //范围判断    if(current_page>total_page) {        current_page = total_page;    }    //当前页的前后各显示多少页    var count = Math.floor(num/2);    var page_html = "";    if(total_page<=1) {        //只有一页        page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=1">1</a></li>‘;    }else if(total_page<=num) {        //把页数全部显示出来        for(var i=1;i<=total_page;i++) {            page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+i+‘>‘+i+‘‘;        }    }else {        if(current_page-count>1) {            //显示前一页按钮            page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+(current_page-count-1)+‘"><i class="fa fa-chevron-left"></i></a></li>‘;        }        //显示当前页前面的页码按钮        for(var i=count;i>=1;i--) {            if(current_page-i>0){                page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+(current_page-i)+‘">‘+(current_page-i)+‘</a></li>‘;            }        }        //当前页按钮        page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+current_page+‘">‘+current_page+‘</a></li>‘;        //显示当前页后面的页码按钮        for(var j=1;j<=count;j++){            if((current_page+j)<=total_page){                page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+(current_page+j)+‘">‘+(current_page+j)+‘</a></li>‘;            }        }        if(current_page+count<total_page){            //显示后一页按钮            page_html += ‘<li><a class="paginator-button" href="http://www.mamicode.com/?page=‘+(current_page+count+1)+‘"><i class="fa fa-chevron-right"></i></a></li>‘;        }    }    return page_html;}

 

 

效果图:

1)总页数10,当前页5,页面显示分页按钮数7

get_page_html(10,5,7)

2)总页数10,当前页1,页面显示分页按钮数7

get_page_html(10,1,7)

2)总页数10,当前页10,页面显示分页按钮数7

get_page_html(10,10,7)

这里的效果是当前页前后各显示3个分页按钮