Home  >  Article  >  Web Front-end  >  Interesting JavaScript questions: Front-end paging

Interesting JavaScript questions: Front-end paging

黄舟
黄舟Original
2017-01-22 14:52:441444browse

Paging on the front end is a very cool thing. It can relieve the pressure on the server side, reduce the number of requests and the amount of server calculations.

However, you need to make it into a component so that it can be easily called everywhere. Otherwise, it would be thankless to write one for every page.

It is best to implement such a helper class, as shown below:

//第一个参数是要分页的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

Whether it is front-end paging or back-end paging, the idea is the same, both are relatively simple, but you must pay attention to illegal value processing.

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;  
}

The above is the interesting JavaScript question: the content of front-end paging. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn