0%

Native JavaScript pagination code

  • Chinese:

There are many mature frameworks for JS pagination, but many small projects are not necessary to “kill the chicken with a slaughter knife”. Here we introduce a JS pagination code for your own use.

First of all, the effect is as follows.

The idea of this pagination is to first display the current page, then print 3 pages before and after the current page as the centre, and finally print the “previous” and “first” page, “last” page “ and “next page”. If the middle pages are not connected, print “…” .

The style is simply achieved using the a tag, the specific code is as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @param {Object} page Current page
* @param {Object} type Article type
* @param {Object} total Total number of pages
* @param {Object} url Head site
*/
function showPage(page,type,total,url) {
page=parseInt(page);
total=parseInt(total);
var str = '<span class="current">' + page + '</span>';

for (var i = 1; i <= 3; i++) {
if (page - i > 1) {
str = '<a href='+url+'?type='+type+'&page='+(page - i) +'>' + (page - i) + '</a> ' + str;
}
if (page + i < total) {
str = str + ' ' +'<a href='+url+'?type='+type+'&page='+(page + i) +'>'+ (page + i)+ '</a> ';
}
}

if (page - 4 > 1) {
str = '<a href="javascript:void(0)">...</a> ' + str;
}

if (page > 1) {
str = '<a href='+url+'?type='+type+'&page='+(page - 1) +'>' +'<Previous page '+'</a> ' +
'<a href='+url+'?type='+type+'&page='+1 +'>'+ 1 + '</a> ' + str;
}

if (page + 4 < total) {
str = str + '<a href="javascript:void(0)">...</a> ';
}

if (page < total) {
str = str + ' ' + '<a href='+url+'?type='+type+'&page='+(total) +'>' +total+ '</a> '+
'<a href='+url+'?type='+type+'&page='+(page + 1) +'>'+' Next page >'+ '</a> ';
}

return str;
}