jquery 分页代码中的小问题

问题描述 投票:0回答:1

为了使这段代码完美运行,我已经工作了一段时间。 所以我做的一切都很好,除了分页按钮 恐怕我必须在这里发布整个代码:

$(document).ready(function() {

var pager = new Pager('comments', 3); 
        pager.init(); 
        pager.showPageNav('Pager', 'pageNavPosition'); 
        pager.showPage(3);  



function Pager(class_name, itemsPerPage) {
    this.class_name = class_name;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;

    this.showRecords = function(from, to) {        
        var rows = $('.' + class_name);
        // i starts from 1 to skip table header row
        for (var i = 0; i < rows.length; i++) {
            if (i < from || i > to)  
                rows[i].style.display = 'none';
            else
                rows[i].style.display = '';
        }
    }

    this.showPage = function(pageNumber) {
        if (! this.inited) {
            alert("not inited");
            return;
        }

        var oldPageAnchor = document.getElementById('pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';

        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';

        var from = (pageNumber - 1) * itemsPerPage;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }   

    this.prev = function() {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    }

    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }                        

    this.init = function() {
        var rows = $('.' + class_name);
        var records = (rows.length); 
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }

    this.showPageNav = function(pagerName, positionId) {
        if (! this.inited) {
            alert("not inited");
            return;
        }

我的问题就在这里:

     var element = document.getElementById(positionId);

        var pagerHtml = '<span onClick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
        for (var page = 1; page <= this.pages; page++)
            pagerHtml += '<span id="pg' + page + '" class="pg-normal" onClick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
        pagerHtml += '<span onClick="'+pagerName+'.next();" class="pg-normal"> Next &#187;</span>';

        element.innerHTML = pagerHtml;
    }
}
                             });

如果您想查看演示,请点击以下链接 http://jsfiddle.net/J3Qnx/11/

jquery pagination
1个回答
0
投票

http://jsfiddle.net/justiceerolin/tes5N/

在 $.ready 中创建寻呼机不会全局创建它,因此在 $.ready 完成后(点击等)它将无法引用寻呼机

解决方案是创建一个全局寻呼机实例 thisPager,并引用该实例。

更改的是前四行:

window.thisPager= new Pager('comments', 3); 
thisPager.init(); 
thisPager.showPageNav('thisPager', 'pageNavPosition'); 
thisPager.showPage(3);  
© www.soinside.com 2019 - 2024. All rights reserved.