用Javascript创建一个分页助手

今天我们要创建一个简单的分页助手脚本,当我们运行脚本时,脚本将返回到输出以下。

页数 – >返回该网站的总页数,给出每页的总元素数。
项目计数 – >返回该网站的总项目。
页面项目计数 – >返回该特定页面中的总项目,例如页面0有10个项目,依此类推。
页面索引 – >这将返回给定项目索引(从零开始)的页面索引。

PaginationHelper函数将采用两个参数,一组页面元素和每页总元素。

让我们通过下面的组合

var helper = new PaginationHelper(['a','b','c','d','e','f'], 3);

我们有六个元素,每个页面包含三个元素。

以下是PaginationHelper函数的完整代码。

// The constructor takes in an array of items and a integer indicating how many
// items fit within a single page
function PaginationHelper(collection, itemsPerPage){
	
    this.itemi_count = collection.length;
    this.page_count = this.itemi_count/itemsPerPage - parseInt(this.itemi_count/itemsPerPage);
    if(this.page_count > 0.0)
        this.page_count = parseInt(this.itemi_count/itemsPerPage) + 1;
    else
        this.page_count = parseInt(this.itemi_count/itemsPerPage);
    this.perpage = itemsPerPage;
    this.page_items = collection;
  
}

// returns the number of items within the entire collection
PaginationHelper.prototype.itemCount = function() {
	
     return this.itemi_count;
  
}

// returns the number of pages
PaginationHelper.prototype.pageCount = function() {
	
     return this.page_count;
  
}

// returns the number of items on the current page. page_index is zero based.
// this method should return -1 for pageIndex values that are out of range
PaginationHelper.prototype.pageItemCount = function(pageIndex) {
	
     if(pageIndex == 0)
         return this.perpage;
     else if(pageIndex > 0 && pageIndex < this.page_count)
	 return (this.itemi_count - (pageIndex * this.perpage));
     else if(pageIndex >= this.page_count)
	 return -1;
  
}

// determines what page an item is on. Zero based indexes
// this method should return -1 for itemIndex values that are out of range
PaginationHelper.prototype.pageIndex = function(itemIndex) {
	
    if(itemIndex < this.itemi_count && itemIndex >= 0)
        return parseInt(itemIndex/this.perpage);
    return -1;
  
}

当我们用var helper = new PaginationHelper([‘a’,’b’,’c’,’d’,’e’,’f’])运行上面的代码时,我们得到

console.log(helper.pageCount()) // 2
console.log(helper.itemCount()) // 6
console.log(helper.pageItemCount(0)) // 3
console.log(helper.pageItemCount(1)) // 3
console.log(helper.pageItemCount(2)) // -1

console.log(helper.pageIndex(5)) // 1
console.log(helper.pageIndex(2)) // 0
console.log(helper.pageIndex(20)) // -1
console.log(helper.pageIndex(-10)) // -1

正如你所看到的,当索引超出范围时,程序将简单地返回-1。

你喜欢这个博客吗?如果是这样,那么继续并通过下面的表格免费订阅它。这个网站是横幅广告免费的博客,为您和我这样的程序员谈论编程,软件和在线工作机会。谢谢.

””

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of