>  기사  >  웹 프론트엔드  >  흥미로운 JavaScript 질문: 프런트엔드 페이징

흥미로운 JavaScript 질문: 프런트엔드 페이징

黄舟
黄舟원래의
2017-01-22 14:52:441511검색

프런트 엔드에서의 페이징은 서버 측의 부담을 완화하고 요청 수와 서버 계산량을 줄일 수 있는 멋진 기능입니다.

단, 어디에서나 쉽게 호출할 수 있도록 컴포넌트로 만들어야 합니다. 그렇지 않으면 페이지마다 세트를 작성하는 것이 고마울 것입니다.

다음과 같이 이러한 도우미 클래스를 구현하는 것이 가장 좋습니다.

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

프런트 엔드 페이징이든 백엔드 페이징이든 아이디어는 동일하며 둘 다 비교적 간단합니다. , 그러나 불법적인 가치처리에 주의해야 합니다.

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

위는 흥미로운 JavaScript 질문입니다: 프런트엔드 페이징 내용에 대한 자세한 내용은 PHP 중국어 웹사이트(www.php.cn)를 참고하세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.