分页技术的几种实现方法

1.原生js table实现分页

实现如图所示分页:
这里写图片描述



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>原生js实现分页-jq22.com</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<table id="table1" width="500" cellspacing="1" cellpadding="5" border="0" bgcolor="#999999">
    <tbody id="table2">

        <tr>
            <th bgcolor="#FFFFFF">编号</th>
            <th bgcolor="#FFFFFF">姓名</th>
            <th bgcolor="#FFFFFF">职业</th>
            <th bgcolor="#FFFFFF">薪金</th>
            <th bgcolor="#FFFFFF">联系电话</th>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">1</td>
            <td bgcolor="#FFFFFF">张三</td>
            <td bgcolor="#FFFFFF">学生</td>
            <td bgcolor="#FFFFFF">10</td>
            <td bgcolor="#FFFFFF">1831111111</td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">2</td>
            <td bgcolor="#FFFFFF">李四</td>
            <td bgcolor="#FFFFFF">游戏玩家</td>
            <td bgcolor="#FFFFFF">40000</td>
            <td bgcolor="#FFFFFF">1222222225</td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">3</td>
            <td bgcolor="#FFFFFF">李爱</td>
            <td bgcolor="#FFFFFF">程序员</td>
            <td bgcolor="#FFFFFF">10000</td>
            <td bgcolor="#FFFFFF">12666666665</td>
        </tr>
       <tr>
            <td bgcolor="#FFFFFF">4</td>
            <td bgcolor="#FFFFFF">范冰冰</td>
            <td bgcolor="#FFFFFF">演员</td>
            <td bgcolor="#FFFFFF">4000000</td>
            <td bgcolor="#FFFFFF">18888888888</td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">5</td>
            <td bgcolor="#FFFFFF">李晨</td>
            <td bgcolor="#FFFFFF">演员</td>
            <td bgcolor="#FFFFFF">600000</td>
            <td bgcolor="#FFFFFF">14342322225</td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">6</td>
            <td bgcolor="#FFFFFF">赵四</td>
            <td bgcolor="#FFFFFF">二人转</td>
            <td bgcolor="#FFFFFF">40000</td>
            <td bgcolor="#FFFFFF">14543452225</td>
        </tr>
       <tr>
            <td bgcolor="#FFFFFF">7</td>
            <td bgcolor="#FFFFFF">刘晓</td>
            <td bgcolor="#FFFFFF">经理</td>
            <td bgcolor="#FFFFFF">10000</td>
            <td bgcolor="#FFFFFF">13234323258</td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">8</td>
            <td bgcolor="#FFFFFF">李四</td>
            <td bgcolor="#FFFFFF">游戏玩家</td>
            <td bgcolor="#FFFFFF">40000</td>
            <td bgcolor="#FFFFFF">12222228888</td>
        </tr>
         <tr>
            <td bgcolor="#FFFFFF">9</td>
            <td bgcolor="#FFFFFF">张三</td>
            <td bgcolor="#FFFFFF">学生</td>
            <td bgcolor="#FFFFFF">10</td>
            <td bgcolor="#FFFFFF">1831111111</td>
        </tr>

    </tbody>
</table>
<span id="spanFirst">第一页</span> <span id="spanPre">上一页</span> <span id="spanNext">下一页</span> <span id="spanLast">最后一页</span><span id="spanPageNum"></span>页/共<span id="spanTotalPage"></span><script>
var theTable = document.getElementById("table2");
var totalPage = document.getElementById("spanTotalPage");
var pageNum = document.getElementById("spanPageNum");

var spanPre = document.getElementById("spanPre");
var spanNext = document.getElementById("spanNext");
var spanFirst = document.getElementById("spanFirst");
var spanLast = document.getElementById("spanLast");

var numberRowsInTable = theTable.rows.length;
var pageSize = 5;
var page =1;

//下一页
function next() {
    hideTable();
    currentRow = pageSize * page;
    maxRow = currentRow + pageSize;
    if (maxRow > numberRowsInTable) maxRow = numberRowsInTable;
    for (var i = currentRow; i < maxRow; i++) {

        theTable.rows[i].style.display = '';
    }
    page++;

    if (maxRow == numberRowsInTable) {
        nextText();
        lastText();
    }
    showPage();
    preLink();
    firstLink();
}

//上一页
function pre() {
    hideTable();
    page--;
    currentRow = pageSize * page;
    maxRow = currentRow - pageSize;
    if (currentRow > numberRowsInTable) currentRow = numberRowsInTable;
    for (var i = maxRow; i < currentRow; i++) {
        theTable.rows[i].style.display = '';
    }

    if (maxRow == 0) {
        preText();
        firstText();
    }
    showPage();
    nextLink();
    lastLink();
}

//第一页
function first() {
    hideTable();
    page = 1;
    for (var i = 0; i < pageSize; i++) {
        theTable.rows[i].style.display = '';
    }
    showPage();
    preText();
    nextLink();
    lastLink();
}

//最后一页
function last() {
    hideTable();
    page = pageCount();
    currentRow = pageSize * (page - 1);
    for (var i = currentRow; i < numberRowsInTable; i++) {
        theTable.rows[i].style.display = '';
    }
    showPage();
    preLink();
    nextText();
    firstLink();
}

function hideTable() {
    for (var i = 0; i < numberRowsInTable; i++) {
        theTable.rows[0].style.display = '';
        theTable.rows[i].style.display = 'none';
    }
}

function showPage() {
    pageNum.innerHTML = page;
}


//总共页数
function pageCount() {
    var count = 0;
    if (numberRowsInTable % pageSize != 0) count = 1;
    return parseInt(numberRowsInTable / pageSize) + count;
}

//显示链接
function preLink() {
    spanPre.innerHTML = "<a href='javascript:pre();'>上一页</a>";
}

function preText() {
    spanPre.innerHTML = "上一页";
}

function nextLink() {
    spanNext.innerHTML = "<a href='javascript:next();'>下一页</a>";
}

function nextText() {
    spanNext.innerHTML = "下一页";
}


function firstLink() {
    spanFirst.innerHTML = "<a href='javascript:first();'>第一页</a>";
}

function firstText() {
    spanFirst.innerHTML = "第一页";
}

function lastLink() {
    spanLast.innerHTML = "<a href='javascript:last();'>最后一页</a>";
}

function lastText() {
    spanLast.innerHTML = "最后一页";
}

//隐藏表格
function hide() {
    for (var i = pageSize; i < numberRowsInTable; i++) {
        theTable.rows[i].style.display = 'none';
    }

    totalPage.innerHTML = pageCount();
    pageNum.innerHTML = '1';

    nextLink();
    lastLink();
}
hide();
</script>

</body>
</html>

2.jquery simplePagination简单的自动分页

项目结构图:
这里写图片描述这里写图片描述

01注:下载项目源码
3.1 jquery.simplePagination.js

在jquery.simplePagination.js只需获取点击按钮对应页码即可,其它参数无需关注!

//获取 href 属性中跟在问号后面的部分
var url = window.location.search;
//比如获取http://localhost:8083/SSMProject/findCustomers?page=1
//获取的是page变量中的值,并设置为currentPage属性值
var pagenumber = url.substring(url.lastIndexOf('=')+1, url.length);
/**
* simplePagination.js v1.5
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

    var methods = {
        init: function(options) {
            //获取 href 属性中跟在问号后面的部分
            var url = window.location.search;
            /*获取当前请求url中的变量值。比如:http://localhost:8083/SSMProject/findCustomers?page=4
              获取的是page变量中的值
             */
            var pagenumber = url.substring(url.lastIndexOf('=')+1, url.length);
            var o = $.extend({
                items:1,//无需关注此数据
                itemsOnPage:1,//无需关注此数据
                pages: 0,//无需关注此数据
                displayedPages: 5,//无需关注此数据
                edges: 2,//无需关注此数据
                currentPage: pagenumber,//重点:当前页码,通过获取href中的page属性值
                hrefTextPrefix: 'findCustomers?page=',//重点:点击分页按钮获取服务器处理
                hrefTextSuffix: '',
                prevText: '上一页',
                nextText: '下一页',
                ellipseText: '&hellip;',
                cssStyle: 'light-theme',
                selectOnClick: true,
                onPageClick: function(pageNumber, event) {
                    // Callback triggered when a page is clicked
                    // Page number is given as an optional parameter
                },
                onInit: function() {
                    // Callback triggered immediately after initialization
                }
            }, options || {});

            var self = this;

            o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
            o.currentPage = o.currentPage - 1;
            o.halfDisplayed = o.displayedPages / 2;

            this.each(function() {
                self.addClass(o.cssStyle + ' simple-pagination').data('pagination', o);
                methods._draw.call(self);
            });

            o.onInit();

            return this;
        },
        //选择跳转第几页
        selectPage: function(page) {
            methods._selectPage.call(this, page - 1);
            return this;
        },
        //前一页
        prevPage: function() {
            var o = this.data('pagination');
            if (o.currentPage > 0) {
                methods._selectPage.call(this, o.currentPage - 1);
            }
            return this;
        },
        //后一页
        nextPage: function() {
            var o = this.data('pagination');
            //当前页小于最后一页减1时,当前页码加一
            if (o.currentPage < o.pages - 1) {
                methods._selectPage.call(this, o.currentPage + 1);
            }
            return this;
        },
        //总页数
        getPagesCount: function() {
            return this.data('pagination').pages;
        },
        //获取当前页
        getCurrentPage: function () {
            return this.data('pagination').currentPage + 1;
        },

        destroy: function(){
            this.empty();
            return this;
        },

        redraw: function(){
            methods._draw.call(this);
            return this;
        },

        disable: function(){
            var o = this.data('pagination');
            o.disabled = true;
            this.data('pagination', o);
            methods._draw.call(this);
            return this;
        },

        enable: function(){
            var o = this.data('pagination');
            o.disabled = false;
            this.data('pagination', o);
            methods._draw.call(this);
            return this;
        },

        _draw: function() {
            var o = this.data('pagination'),
                interval = methods._getInterval(o),
                i;

            methods.destroy.call(this);

            var $panel = this.prop("tagName") === "UL" ? this : $('<ul></ul>').appendTo(this);

            // Generate Prev link
            if (o.prevText) {
                methods._appendItem.call(this, o.currentPage - 1, {text: o.prevText, classes: 'prev'});
            }

            // Generate start edges
            if (interval.start > 0 && o.edges > 0) {
                var end = Math.min(o.edges, interval.start);
                for (i = 0; i < end; i++) {
                    methods._appendItem.call(this, i);
                }
                if (o.edges < interval.start && (interval.start - o.edges != 1)) {
                    $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                } else if (interval.start - o.edges == 1) {
                    methods._appendItem.call(this, o.edges);
                }
            }

            // Generate interval links
            for (i = interval.start; i < interval.end; i++) {
                methods._appendItem.call(this, i);
            }

            // Generate end edges
            if (interval.end < o.pages && o.edges > 0) {
                if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
                    $panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
                } else if (o.pages - o.edges - interval.end == 1) {
                    methods._appendItem.call(this, interval.end++);
                }
                var begin = Math.max(o.pages - o.edges, interval.end);
                for (i = begin; i < o.pages; i++) {
                    methods._appendItem.call(this, i);
                }
            }

            // Generate Next link
            if (o.nextText) {
                methods._appendItem.call(this, o.currentPage + 1, {text: o.nextText, classes: 'next'});
            }
        },

        _getInterval: function(o) {
            return {
                start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
                end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
            };
        },

        _appendItem: function(pageIndex, opts) {
            var self = this, options, $link, o = self.data('pagination'), $linkWrapper = $('<li></li>'), $ul = self.find('ul');

            pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

            options = $.extend({
                text: pageIndex + 1,
                classes: ''
            }, opts || {});

            if (pageIndex == o.currentPage || o.disabled) {
                if (o.disabled) {
                    $linkWrapper.addClass('disabled');
                } else {
                    $linkWrapper.addClass('active');
                }
                $link = $('<span class="current">' + (options.text) + '</span>');
            } else {
                $link = $('<a href="' + o.hrefTextPrefix + (pageIndex + 1) + o.hrefTextSuffix + '" class="page-link">' + (options.text) + '</a>');
                $link.click(function(event){
                    return methods._selectPage.call(self, pageIndex, event);
                });
            }

            if (options.classes) {
                $link.addClass(options.classes);
            }

            $linkWrapper.append($link);

            if ($ul.length) {
                $ul.append($linkWrapper);
            } else {
                self.append($linkWrapper);
            }
        },

        _selectPage: function(pageIndex, event) {
            var o = this.data('pagination');
            o.currentPage = pageIndex;
            if (o.selectOnClick) {
                methods._draw.call(this);
            }
            return o.onPageClick(pageIndex + 1, event);
        }

    };

    $.fn.pagination = function(method) {

        // Method calling logic
        if (methods[method] && method.charAt(0) != '_') {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.pagination');
        }

    };

})(jQuery);
3.2CustomerController.java
MySql数据库实现分页查询的SQL语句写法:

一:分页需求:

客户端通过传递start(页码),limit(每页显示的条数)两个参数去分页查询数据库表中的数据,那我们知道MySql数据库提供了分页的函数limit m,n,但是该函数的用法和我们的需求不一样,所以就需要我们根据实际情况去改写适合我们自己的分页语句,具体的分析如下:

比如:

查询第1条到第10条的数据的sql是:select * from table limit 0,10; ->对应我们的需求就是查询第一页的数据:select * from table limit (1-1)*10,10;

查询第10条到第20条的数据的sql是:select * from table limit 10,20; ->对应我们的需求就是查询第二页的数据:select * from table limit (2-1)*10,10;

查询第20条到第30条的数据的sql是:select * from table limit 20,30; ->对应我们的需求就是查询第三页的数据:select * from table limit (3-1)*10,10;

二:通过上面的分析,可以得出符合我们自己需求的分页sql格式是:select * from table limit (start-1)*limit,limit; 其中start是页码,limit是每页显示的条数。

 package com.wang.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wang.po.Customer;
import com.wang.service.CustomerService;
@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerservice;

    //jquery.simplePagination.js中的方法向服务器发送请求,并带有page请求参数
    @RequestMapping(value="/findCustomers",method=RequestMethod.GET)
    public String findCustomers(@RequestParam(defaultValue="!") Integer page, Model model) {
        System.out.println("前端发送的请求页码是="+page);
        //page1表示:页码
        Integer page1=(page-1)*5;
        System.out.println(page1);
        List<Customer> customers = customerservice.findCustomers(page1);

        if(customers.size()==0) {
            System.out.println("对不起!服务器没有你想要的数据!");
        }
        model.addAttribute("customers", customers);
        return "customer";

    }
}
3.3customer.jsp
参数说明
items表示数据表中的总记录条数,需要sql中的count(id)计算出来。
itemsOnPage表示每页显示记录条数,可以手动设置。
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery翻页插件simplePagination</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.simplePagination.js"></script>
<link type="text/css" rel="stylesheet" href="css/simplePagination.css"/>
<style type="text/css">
a{text-decoration:none}
.page{margin:30px auto;width:620px}
</style>
</head>
<body>
    <table border=1>
        <tr>
            <th style="width: 100px;">编号</th>
            <th style="width: 100px;">姓名</th>
            <th style="width: 100px;">职业</th>
            <th style="width: 100px;">薪水</th>
            <th style="width: 100px;">电话</th>
        </tr>
        <c:forEach items="${customers}" var="customer">
            <tr >
                <td align="center">${customer.id}</td>
                <td align="center">${customer.username}</td>
                <td align="center">${customer.jobs}</td>
                <td align="center">${customer.salary}</td>
                <td align="center">${customer.phone}</td>

            </tr>
        </c:forEach>

    </table>
<!-- 引入分页-->    
<div id="paging1" class="page" align="left"></div>
<script type="text/javascript">
$(function(){
    $("#paging1").pagination({
        items: 26,//数据表中的总记录,可以使用SQL语句计算出,这里直接写数据表中的总记录了
        itemsOnPage:5,//每页显示的5条记录,可以自己修改要显示的记录数
        cssStyle: 'light-theme'//分页主题
    });
});
</script>
</body>
</html>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页