Maison > interface Web > js tutoriel > le corps du texte

JavaScript趣题:前端分页

黄舟
Libérer: 2017-01-22 14:52:44
original
1511 Les gens l'ont consulté

在前端进行分页是一件很炫酷的事情,它可以缓解服务器端的压力,减少了请求次数以及服务器计算量。

不过,你得需要把它做成一个组件的形式,这样才方便在各处调用,否则每一个页面都写一套,岂不是费力不讨好?

最好是实现一个这样的帮助类,如下所示:

//第一个参数是要分页的JSON对象  
//第二个参数是每一页的最大项数  
var helper = new PaginationHelper(['a','b','c','d','e','f'], 4);  
//总共多少页 => Math.ceil(6 / 4)  
helper.pageCount(); // 2  
//总共多少项 => array.length  
helper.itemCount(); // 6  
//求当前页的项数,这个页的索引是从0开始的  
helper.pageItemCount(0); // 4  
//6 - 4 = 2  
helper.pageItemCount(1); // 2  
//总共才2页,所以当前页无效,返回-1  
helper.pageItemCount(2); // -1  
  
//当前索引是属于第几页?  
helper.pageIndex(5); // 1  
helper.pageIndex(2); // 0  
//总共都才6条记录,所以20无效  
helper.pageIndex(20); // -1  
//索引小于0,无效返回-1  
helper.pageIndex(-10); // -1
Copier après la connexion

无论是前端分页还是后端分页,思路是一样的,都比较简单,不过得注意对非法值的处理。

function PaginationHelper(collection, itemsPerPage){  
    this.collection = collection;  
    this.itemsPerPage = itemsPerPage;  
}  
  
PaginationHelper.prototype.itemCount = function() {  
    return this.collection.length;  
}  
  
PaginationHelper.prototype.pageCount = function() {  
    return Math.ceil(this.itemCount() / this.itemsPerPage);  
}  
  
PaginationHelper.prototype.pageItemCount = function(pageIndex) {  
    if(pageIndex < this.pageCount() - 1){  
        return this.itemsPerPage;  
    }  
    else if(pageIndex == this.pageCount() - 1){  
        return this.itemCount() - pageIndex * this.itemsPerPage;  
    }  
    else{  
        return -1;  
    }  
}  
  
PaginationHelper.prototype.pageIndex = function(itemIndex) {  
    if(itemIndex >=0 && itemIndex < this.itemCount()){  
        return Math.floor(itemIndex / this.itemsPerPage);  
    }  
    return -1;  
}
Copier après la connexion

以上就是JavaScript趣题:前端分页的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!