时间:2022-02-09 09:24:21 | 栏目:JavaScript代码 | 点击:次
有些项目业务比较简单,但用到前端分页的地方又比较多,插件的体积比较难控制用起来也麻烦,所以自己写一个简易的。
通过 jQuery.slice() 选择子集的区间元素, 然后控制显示隐藏来实现;
假设每页显示数量为x,当前页码为y,元素索引从0开始,那么显示的区间即为 x(y-1) 到 xy。
demo代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>前端分页实现demo</title> </head> <body> <div class="parent"> <ul class="box" style="min-height: 147px;"> </ul> <div class="page-box"> <button class="page-btn prev">上一页</button> <span class="page-num">1/1</span> <button class="page-btn next">下一页</button> </div> </div> <div class="parent"> <ul class="box2" style="min-height: 63px;"> </ul> <div class="page-box"> <button class="page-btn prev">上一页</button> <span class="page-num">1/1</span> <button class="page-btn next">下一页</button> </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> /** * 分页初始化 * @param {*} eleBox 需要被分页的容器 * @param {*} size 每页的条数 */ function InitPagination(eleBox, size) { var box = $(eleBox), children = box.children(), total = children.length, pageBox = box.next(), pageNum = pageBox.find('.page-num'), maxNum = !Math.ceil(total / size) ? 1 : Math.ceil(total / size); pageNum.text('1/' + maxNum); children.hide(); children.slice(0, size).show(); pageBox.off().on('click', '.prev, .next', function (e) { var nowNum = parseInt(pageNum.text().split('/')[0]); if ($(this).hasClass('prev')) { nowNum--; if (nowNum < 1) { nowNum = 1 return; } } else { nowNum++; if (nowNum > maxNum) { nowNum = maxNum return; } } children.hide(); children.slice(size * (nowNum - 1), nowNum * size).show(); pageNum.text(nowNum + '/' + maxNum); }) } // 模拟数据写入 var box = $('.box'), box2 = $('.box2'), li = ''; for (let i = 0; i < 16; i++) { li += '<li>' + i + '</li>' } box.html(li); box2.html(li); // 实例化分页器 new InitPagination(box, 7) new InitPagination(box2, 3) </script> </body> </html>