将最近项目中自行编写的分页功能源码贴起来,实际使用发现非常方便,执行过程流畅,逻辑也通用。效果就是对页面上的整个Table进行分页每页20条,非AJAX方式。在大型列表需要填写并post保存时这样的分页尤其方便。

调用方法:hanaGridPager(【含有table的div的id】,【到第x页】)

*注意table内要有tbody标签,否则请把totalRow计算那里逻辑自行修改。最后就是table外面要有一层div,div的id写入第一个参数中。

function hanaGridPager(container, toPage) {
    var $container = $(container)
    var totalRows = $('table', $container).find("tbody tr").length;
    var totalPages = parseInt(totalRows / 20 + (totalRows % 20 != 0 ? 1 : 0));
    $container.find(container + "_pager").remove();
    $container.append("<div id='" + container.replace("#", "") + "_pager' class=\"buttondiv\">共" + totalRows + "条记录 &nbsp; 当前第" + toPage + "页 &nbsp; 共" + totalPages + "页 </div>");

    //页码前显示5个,后显示5个
    for (var i = 0; i < (totalPages > 10 ? 10 : totalPages); i++) {
        if (totalPages < 10) {
            $(container + "_pager").append("<a class=\"pager" + ((i + 1) == toPage ? "current" : "") + "\" href=\"javascript:hanaGridPager('" + container + "'," + (i + 1) + "); \">" + (i + 1) + "</a>");
        } else if (i <= 5) {
            if (toPage - 5 + i >= 1) {
                $(container + "_pager").append("<a class=\"pager" + ((toPage - 5 + i) == toPage ? "current" : "") + "\" href=\"javascript:hanaGridPager('" + container + "'," + (toPage - 5 + i) + "); \">" + (toPage - 5 + i) + "</a>");
            }
        } else if ((toPage - 5 + i) <= totalPages) {
            $(container + "_pager").append("<a class=\"pager\" href=\"javascript:hanaGridPager('" + container + "'," + (toPage - 5 + i) + "); \">" + (toPage - 5 + i) + "</a>");
        }
    }

    //显示具体条目
    $('table', $container).find("tbody tr").hide();
    for (var i = 1; i <= (totalRows < 20 ? totalRows : 20); i++) {
        $('table', $container).find("tbody tr:eq(" + (toPage * 20 + (i - 1) - 20) + ")").show();
    }
}