分页功能使用手柄js [英] Pagination Functionality using handlebars js
问题描述
感谢您的善意帮助!
p>谢谢 一些代码示例:
$(function(){
var opts = {
pageMax:5,
postsDiv:$('#posts'),
dataUrl:searchResult.json
}
函数范围(i){return i?range(i - 1)。 concat(i):[]}
function loadPosts(posts){
opts.postsDiv.empty();
posts.each(function(){
var source = $(#post-template)。html();
var temp后期= Handlebars.compile(来源);
var context = {
title:this.title,
desc:this.body,
};
var html = template(context);
opts.postsDiv.append(html);
});
}
function paginate(pageCount){
var source = $(#pagination-template)。html();
var template = Handlebars.compile(source);
var context = {pages:range(pageCount)};
var html = template(context);
opts.postsDiv.after(html);
function changePage(pageNumber){
pageItems.removeClass('active');
pageItems.filter('[data-page =''+ pageNumber +']')。addClass('active');
loadPosts(data.slice(pageNumber * opts.pageMax - opts.pageMax,pageNumber * opts.pageMax));
}
var pageItems = $('。pagination> li.pagination-page');
$ b pageItems.on('click',function(){
changePage(this.getAttribute('data-page'));
})。filter('[data -page = 1] ')addClass(' 激活); ('click',function(){
gotoPageNumber = parseInt($('。pagination> li.active')
$ b $('。pagination> li.pagination-prev'如果(gotoPageNumber< = 0){gotoPageNumber = pageCount;}
changePage(gotoPageNumber);
}); ('click',function(){
gotoPageNumber = parseInt($('。pagination> li.active')
$ b $('。pagination> li.pagination-next'如果(gotoPageNumber> pageCount){gotoPageNumber = 1;}
changePage(gotoPageNumber);
});
$ b $ .ajax({
dataType:'json',
url:opts.dataUrl,
success:function(response_json){
data = $(response_json.records.page);
dataCount = data.length;
pageCount = Math.ceil(dataCount / opts.pageMax);
if(dataCount> opts.pageMax){
paginate(pageCount);
posts = data.slice(0,opts.pageMax);
} else {
posts = data;
}
loadPosts(posts);
}
});
});
几个月前我必须解决类似的问题。我从kottenator发现这个Gist 。
您的范围函数因此被修改,其中 c
是当前页面,并且 m
您的 PAGECOUNT
。对函数的调用已被修改了一些,并且还添加了对 paginate(...)
函数的递归调用,以在导航之后重新计算标记(同样,分支是添加到您的DOM附加函数调用中,修改分页标记,我使用了三元运算符。可能会更优雅地实现这一点)。
查看此CodePen
函数范围(c,m){
var current = c || 1,
last = m,
delta = 2,
left = current - delta,
right = parseInt(current)+ delta + 1,
range = [ ],
rangeWithEllipsis = [],
l,
t;
range.push(1);如果(i> = left& i< right& i<< i& m&& i> 1){
range.push(i);
}
}
range.push(m);
for(var i of range){
if(l){
if(i - l === 2){
t = l + 1;
rangeWithEllipsis.push(t);
} else if(i - l!== 1){
rangeWithEllipsis.push(...);
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
}
它并不能准确解决您的问题,但它可以正确分页
如果我有一段时间,我会尝试按照确切的方式进行分页(这实际上只是关于自定义 delta
, left
和 right
操作数,然后改变你的分页和分页prev事件处理程序调用)。 p>
编辑我改变了算法,找到 left
和
边界。您的 index.html
也被修改了一些。
这个想法是以5的倍数计算左右边界。然后创建一个如果差别太大,则显示和添加省略号的索引范围。这应该能够有效解决您的原始问题。
$ b JavaScript $ b
getFirstDigits =(t)=> {
return parseInt(t.toString()。slice(0,-1))
}
getLastDigit =(t)=> {
return parseInt(t.toString()。slice(-1))
}
isMultipleOf5 =(t)=> {
return [0,5] .reduce((res,curr)=> {
return res = res || curr === getLastDigit(t);
},false) ;
}
isBetween0and5 =(t)=> {
const _t = getLastDigit(t);
return _t< 5;
}
isBetween5and9 =(t)=> {
const _t = getLastDigit(t);
return _t => 5&& _t <= 9;
}
appendDigit =(t,d)=> {
return parseInt(getFirstDigits(t).toString()+ d.toString())
}
getSecondRightMostDigit =(t)=> {
return parseInt(t.toString()。slice(-2,-1))
}
incrementSecondDigit =(t)=> {
return t + 10;
}
getLeft =(t)=> {
if(t> = 10){
if(isBetween0and5(t))return appendDigit(t,0);
else返回appendDigit(t,5);
} else {
if(t <5)return 0;
else返回5;
}
}
getRight =(t)=> {
if(t <5)return 5;
else if(t <10)return 10;
else if(isBetween0and5(t))return appendDigit(t,5)
else return appendDigit(incrementSecondDigit(t),0);
}
函数范围(c,m){
var current = c || 1,
last = m,
delta = 2,
left = getLeft(c),
right = getRight(c),
range = [],
rangeWithEllipsis = [],
l,
t;
var rightBoundary = right< 5? 5:正确; (i< m&< i> 0)range.push(i);
for(var i = left; i< rightBoundary; ++ i)
}
range.push(m);
for(var i of range){
if(l){
if(i - l === 2){
t = l + 1;
rangeWithEllipsis.push(t);
} else if(i - l!== 1){
rangeWithEllipsis.push(...);
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
HTML / HandleBars
<!doctype html>
< html lang =en>
< head>
< meta charset =UTF-8>
< title>把手分页< / title>
< link href =main.css =stylesheet/>
< script src =jquery.min.js>< / script>
< script src =handlebars.min.js>< / script>
< script src =functions.js>< / script>
< / head>
< body class =container>
< div id =posts>< / div>
< script id =pagination-templatetype =text / x-handlebars-template>
< ul class =pagination>
< li class =pagination-prev>< a href =#>& laquo;< / a>< / li>
{{#each pages}}
< li class =pagination-pagedata-page ={{this}}>< a href =# > {{此}}< / A>< /锂>
{{/ each}}
< li class =pagination-next>< a href =#>& raquo;< / a>< ; /立GT;
< / ul>
< / script>
< script id =post-templatetype =text / x-handlebars-template>
< div class =分数 - 结构分数 - 第2栏 - 右侧搜索列表帖子>
< div class =score-right>
< h4> {{record_count}}< / h4>
< h5 style =z-index:1;>
< a href =#> {{title}}< / a>
< / h5>
< p style =z-index:1;> {{desc}}< / p>
< / div>
< / div>
< hr>
< / script>
< / body>
< / html>
< script>
$(function(){
var opts = {
pageMax:2,
postsDiv:$('#posts'),
dataUrl:searchResult.json
函数loadPosts(文章){
opts.postsDiv.empty();
posts.each(function(){
var source = $(#post-template)。html();
var template = Handlebars.compile(source);
var context = {
title:this.title,
desc:this.body,
};
var html = template(context);
opts.postsDiv.append(html);
});
hidePrev ();
}
function hidePrev(){$('。pagination .pagination-prev')。hide();}
function showPrev(){$(' .pagination .pagination-prev')。show();}
function hideNext(){$('。pagination .pagination-next ).hide();}
功能showNext(){$(分页.pagination-下。)示出了()。 }
函数paginate(page,pageCount){
var source = $(#pagination-template)。html();
var template = Handlebars.compile(source);
var context = {pages:range(page,pageCount)};
console.log(range(page,pageCount));
var html = template(context);
var paginationTag = opts.postsDiv.parent()。find(。pagination);
paginationTag.length> 0? paginationTag.replaceWith(html):opts.postsDiv.before(html);
function changePage(page){
pageItems.removeClass('active');
pageItems.filter('[data-page =''+ page +']')。addClass('active');
loadPosts(data.slice(page * opts.pageMax - opts.pageMax,page * opts.pageMax));
paginate(page,pageCount);
if(gotoPageNumber< = 1){
hidePrev();
}
}
var pageItems = $('。pagination> li.pagination-page');
var pageItemsLastPage = $('。pagination li')。length - 2;
pageItems.removeClass('active');
pageItems.filter('[data-page =''+ page +']')。addClass('active');
$ b pageItems.on('click',function(){
getDataPageNo = this.getAttribute('data-page')
console.log(getDataPageNo)
changePage(getDataPageNo);
if(getDataPageNo == 1){
hidePrev()
}
else if(getDataPageNo == pageItemsLastPage){
hideNext();
}
else {
showPrev();
showNext();
}
}); ('click',function(){
gotoPageNumber = parseInt($('。pagination> li.active')
$ b $('。pagination> li.pagination-prev' ).attr('data-page')) - 1;
changePage(gotoPageNumber);
}); ('click',function(){
gotoPageNumber = parseInt($('。pagination> li.active')
$ b $('。pagination> li.pagination-next' ).attr('data-page'))+ 1;
if(gotoPageNumber> pageCount){
gotoPageNumber = 1;
showPrev();
}
changePage(gotoPageNumber);
});
$ b $ .ajax({
dataType:'json',
url:opts.dataUrl,
success:function(response_json){
data = $(response_json.records.page);
dataCount = data.length;
pageCount = Math.ceil(dataCount / opts.pageMax);
if(dataCount> opts.pageMax){
paginate(1,pageCount);
posts = data.slice(0,opts.pageMax);
} else {
posts = data;
}
loadPosts(posts);
}
});
});
< / script>
I'am developing a Pagination Functionality using handlebars js and fetching the data from JSON.
First 5 results will be shown on page load.
on click of next pagination another set of 5 results will be displayed and so on.
If i have total number of results 100 by displaying each 5 Results in page. Page Numbers will be 1 of 20.
- if the pagination has more then 5 number of Pages , I want to display "1,2,3 ... last Page Number (20)" same vice versa
- on load Previous Button Should be hidden when ever next page is clicked it has to be enabled.
Request to you please look into this and give some advice / suggestion on this.
Should be Like Below
Appreciate your kind help !
Thanks
some code sample :
$(function () { var opts = { pageMax: 5, postsDiv: $('#posts'), dataUrl: "searchResult.json" } function range(i) { return i ? range(i - 1).concat(i) : [] } function loadPosts(posts) { opts.postsDiv.empty(); posts.each(function () { var source = $("#post-template").html(); var template = Handlebars.compile(source); var context = { title: this.title, desc: this.body, }; var html = template(context); opts.postsDiv.append(html); }); } function paginate(pageCount) { var source = $("#pagination-template").html(); var template = Handlebars.compile(source); var context = { pages: range(pageCount) }; var html = template(context); opts.postsDiv.after(html); function changePage(pageNumber) { pageItems.removeClass('active'); pageItems.filter('[data-page="' + pageNumber + '"]').addClass('active'); loadPosts(data.slice(pageNumber * opts.pageMax - opts.pageMax, pageNumber * opts.pageMax)); } var pageItems = $('.pagination>li.pagination-page'); pageItems.on('click', function () { changePage(this.getAttribute('data-page')); }).filter('[data-page="1"]').addClass('active'); $('.pagination>li.pagination-prev').on('click', function () { gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) - 1; if (gotoPageNumber <= 0) { gotoPageNumber = pageCount; } changePage(gotoPageNumber); }); $('.pagination>li.pagination-next').on('click', function () { gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) + 1; if (gotoPageNumber > pageCount) { gotoPageNumber = 1; } changePage(gotoPageNumber); }); } $.ajax({ dataType: 'json', url: opts.dataUrl, success: function (response_json) { data = $(response_json.records.page); dataCount = data.length; pageCount = Math.ceil(dataCount / opts.pageMax); if (dataCount > opts.pageMax) { paginate(pageCount); posts = data.slice(0, opts.pageMax); } else { posts = data; } loadPosts(posts); } }); });
I had to solve a similar issue a few months ago. I found this Gist from kottenator.
Your range function is modified thusly, with c
being the current page, and m
your pageCount
. Calls to the function have been modified a bit and a recursive call to your paginate(...)
function is also added to recompute the tag after navigation (also, a branch was added to your DOM appending function calls, to modify the pagination tag, I used a ternary operator. There may be more elegant to achieve this).
See this CodePen
function range(c,m) {
var current = c || 1,
last = m,
delta = 2,
left = current - delta,
right = parseInt(current) + delta + 1,
range = [],
rangeWithEllipsis = [],
l,
t;
range.push(1);
for (var i = c - delta ; i <= c + delta ; i++) {
if (i >= left && i < right && i < m && i > 1) {
range.push(i);
}
}
range.push(m);
for (var i of range) {
if (l) {
if (i - l === 2) {
t = l+1;
rangeWithEllipsis.push(t);
} else if (i - l !== 1) {
rangeWithEllipsis.push("...");
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
}
It doesn't solve exactly your problem per say, but it does paginate correctly.
If I have some time, I'll try and make it paginate the exact way you want to (it's really only about customizing the delta
, left
and right
operand in the algorithm, and changing your pagination next and pagination prev event handler calls).
Edit I changed the algorithm to find the left
and right
boundary. Your index.html
is also modified a bit.
The idea is to compute the left and right boundary by multiples of 5. You then create a range of the indexes to show and add an elipsis if the difference is too big. This should effectively solves your original problem.
JavaScript
getFirstDigits = (t) => {
return parseInt(t.toString().slice(0,-1))
}
getLastDigit = (t) => {
return parseInt(t.toString().slice(-1))
}
isMultipleOf5 = (t) => {
return [0,5].reduce((res,curr)=>{
return res = res || curr === getLastDigit(t);
},false);
}
isBetween0and5 = (t) => {
const _t = getLastDigit(t);
return _t < 5;
}
isBetween5and9 = (t) => {
const _t = getLastDigit(t);
return _t => 5 && _t <= 9;
}
appendDigit = (t,d) => {
return parseInt(getFirstDigits(t).toString() + d.toString())
}
getSecondRightMostDigit = (t) => {
return parseInt(t.toString().slice(-2,-1))
}
incrementSecondDigit = (t) => {
return t+10;
}
getLeft = (t) => {
if(t>=10){
if(isBetween0and5(t)) return appendDigit(t,0);
else return appendDigit(t,5);
} else {
if (t<5) return 0;
else return 5;
}
}
getRight = (t) => {
if(t<5) return 5;
else if (t<10) return 10;
else if(isBetween0and5(t)) return appendDigit(t,5)
else return appendDigit(incrementSecondDigit(t),0);
}
function range(c,m) {
var current = c || 1,
last = m,
delta = 2,
left = getLeft(c),
right = getRight(c),
range = [],
rangeWithEllipsis = [],
l,
t;
var rightBoundary = right < 5 ? 5 : right;
for (var i = left ; i < rightBoundary ; ++i) {
if( i < m && i > 0) range.push(i);
}
range.push(m);
for (var i of range) {
if (l) {
if (i - l === 2) {
t = l+1;
rangeWithEllipsis.push(t);
} else if (i - l !== 1){
rangeWithEllipsis.push("...");
}
}
rangeWithEllipsis.push(i);
l = i;
}
return rangeWithEllipsis;
}
HTML/HandleBars
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handlebars Pagination</title>
<link href="main.css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="handlebars.min.js"></script>
<script src="functions.js"></script>
</head>
<body class="container">
<div id="posts"></div>
<script id="pagination-template" type="text/x-handlebars-template">
<ul class="pagination">
<li class="pagination-prev"><a href="#">«</a></li>
{{#each pages}}
<li class="pagination-page" data-page="{{this}}"><a href="#">{{this}}</a></li>
{{/each}}
<li class="pagination-next"><a href="#">»</a></li>
</ul>
</script>
<script id="post-template" type="text/x-handlebars-template">
<div class="score-structural score-column2-wideright search-listings post">
<div class="score-right">
<h4>{{record_count}}</h4>
<h5 style="z-index: 1;">
<a href="#"> {{ title }} </a>
</h5>
<p style="z-index: 1;"> {{ desc }} </p>
</div>
</div>
<hr>
</script>
</body>
</html>
<script>
$(function () {
var opts = {
pageMax: 2,
postsDiv: $('#posts'),
dataUrl: "searchResult.json"
}
function loadPosts(posts) {
opts.postsDiv.empty();
posts.each(function () {
var source = $("#post-template").html();
var template = Handlebars.compile(source);
var context = {
title: this.title,
desc: this.body,
};
var html = template(context);
opts.postsDiv.append(html);
});
hidePrev();
}
function hidePrev() { $('.pagination .pagination-prev').hide(); }
function showPrev() { $('.pagination .pagination-prev').show(); }
function hideNext() { $('.pagination .pagination-next').hide(); }
function showNext() { $('.pagination .pagination-next').show(); }
function paginate(page,pageCount) {
var source = $("#pagination-template").html();
var template = Handlebars.compile(source);
var context = { pages: range(page,pageCount) };
console.log(range(page,pageCount));
var html = template(context);
var paginationTag = opts.postsDiv.parent().find(".pagination");
paginationTag.length > 0 ? paginationTag.replaceWith(html) : opts.postsDiv.before(html);
function changePage(page) {
pageItems.removeClass('active');
pageItems.filter('[data-page="' + page + '"]').addClass('active');
loadPosts(data.slice(page * opts.pageMax - opts.pageMax, page * opts.pageMax));
paginate(page,pageCount);
if (gotoPageNumber <= 1) {
hidePrev();
}
}
var pageItems = $('.pagination>li.pagination-page');
var pageItemsLastPage = $('.pagination li').length - 2;
pageItems.removeClass('active');
pageItems.filter('[data-page="' + page + '"]').addClass('active');
pageItems.on('click', function () {
getDataPageNo = this.getAttribute('data-page')
console.log(getDataPageNo)
changePage(getDataPageNo);
if (getDataPageNo == 1) {
hidePrev()
}
else if (getDataPageNo == pageItemsLastPage) {
hideNext();
}
else {
showPrev();
showNext();
}
});
$('.pagination>li.pagination-prev').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) - 1;
changePage(gotoPageNumber);
});
$('.pagination>li.pagination-next').on('click', function () {
gotoPageNumber = parseInt($('.pagination>li.active').attr('data-page')) + 1;
if (gotoPageNumber > pageCount) {
gotoPageNumber = 1;
showPrev();
}
changePage(gotoPageNumber);
});
}
$.ajax({
dataType: 'json',
url: opts.dataUrl,
success: function (response_json) {
data = $(response_json.records.page);
dataCount = data.length;
pageCount = Math.ceil(dataCount / opts.pageMax);
if (dataCount > opts.pageMax) {
paginate(1,pageCount);
posts = data.slice(0, opts.pageMax);
} else {
posts = data;
}
loadPosts(posts);
}
});
});
</script>
这篇关于分页功能使用手柄js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!