原生js分页

最近工作好忙 工作中也遇到了很多问题 也很久没有更新博客了 闲下来继续更新吧 大家一块学习

项目中要对数据进行分页处理 一般分页我们都用插件 比如elementui bootstrap之类的 但其实原生的我们也应该理解思路 理解思路有点代码功底自己也能调试出来

先看效果

上代码

 样式

<style>
		.pager {
			padding: 0;
			margin: 0;
			white-space: nowrap;
			text-align: center;
		}

		.pager li {
			list-style: none;
			font-family: arial;
			font-size: 14px;
			padding: 2px;
			margin: 5px;
			border: #333 1px solid;
			text-align: center;
			border-radius: 5px;
			max-width: 80px;
			width: 25px;
			height: 22px;
			line-height: 22px;
			cursor: pointer;
			background: #fff;
			display: inline-block
		}

		.pager li:hover {
			border: #a11418 1px solid;
			color: #a11418;
			opacity: 0.8;
		}

		.pager li.pg-hidepage {
			display: none
		}

		.pager li.pg-prev,
		li.pg-next {
			width: 80px
		}

		.pager li.pg-selected {
			border: #a11418 1px solid;
			background: #a11418;
			color: white
		}

		.pager li.pg-selected:hover {
			color: #000;
			cursor: default
		}

		.pager li.pg-dislabel {
			color: #ccc;
			border: #ccc 1px solid;
			cursor: default
		}

		.pager li.pg-dislabel:hover {
			border: #ccc 1px solid
		}
	</style>

body:

<ul class="zblist clear" id="zblist">
								
</ul>
<--分页-->

<div id="pager"></div>

js:

我们首先需要知道一共有多少条数据(分多少页,接口请求来的总数据条数。可以先请求一次接口,拿到总条数)  一页多少条数据  (后端给的参数)

	<script>
			var countnum = 0 //总条数
			var data = {} 
			$.ajax({
				type: "POST",
				url: $.url('f/newsCenter/ajax_article_list'),
				data: {
					categoryId: '82efba2e6b0442f48a10c0f23b17e260',
					pageSize: 40,
					pageNo: 1,
				},
				success: function (res1) {
					if (res1.state == 1) {
						countnum = res1.data.page.count //获取总条数
						//console.log(countnum);
						var pager = document.getElementById("pager");
						var start = 0, end = 0;


						//加载分页
						loadPager(pager, {
							pageSize: 6,//每页显示条数
							totalCount: countnum,//总记录数
							curPage: 1,//当前页数,不设置则默认1
							nav_count: 5,//显示多少个导航
							callback: function (count) {//点击翻页后的回调函数
								data = {
									categoryId: '82efba2e6b0442f48a10c0f23b17e260',
									pageSize: 6,
									pageNo: count,
								}
								getdata()//再次根据分页请求数据
							}
						});
					}
				}
			})
			function loadPager(el, option) {
				var page_ul, pageSize, totalCount, curPage, nav_count, callback, totalPage, pagerId, nav_mid, nav_rela,
					prevName = '上一页', nextName = '下一页', firstName = '首页', lastName = '尾页',
					leftCount = 0, rightCount = 0,
					btn_dislabel = 'pg-dislabel', btn_selected = 'pg-selected', btn_hide = 'pg-hidepage';

				//初始化并设置一些默认值
				init();
				//显示分页
				el.innerHTML = genHtml();

				//给UL添加点击事件
				handleClick();

				//处理按钮
				handleBtn();

				//初次加载响应点击事件
				callback(curPage);

				function init() {
					var $option = option || {};
					pageSize = $option.pageSize || 10;
					totalCount = $option.totalCount || 0;
					curPage = $option.curPage || 1;
					nav_count = $option.nav_count || 0;
					callback = $option.callback || function () { };
					//计算总页数
					totalPage = parseInt(totalCount / pageSize) + ((totalCount % pageSize > 0) ? 1 : 0);
					pagerId = "pager_ul_" + Math.round(Math.random() * (9999 - 1000) + 1000);

					nav_mid = Math.round(nav_count / 2);
				}
				//生成显示分页的html
				function genHtml(pager) {
					var html = "<ul class='pager' id='" + pagerId + "'>";
					html += "<li class='pg-prev' id='first'>" + firstName + "</li>";
					html += "<li class='pg-prev' id='prev'>" + prevName + "</li>";
					for (var i = 0; i < totalPage; i++) {
						var page = (i + 1);
						if (i < nav_count) {//显示 
							html += "<li page='" + page + "' class='pg-showpage'>" + page + "</li>"
						} else {//隐藏
							html += "<li page='" + page + "' class='pg-hidepage'>" + page + "</li>"
						}
					}
					html += "<li class='pg-next' id='next'>" + nextName + "</li>";
					html += "<li class='pg-prev' id='last'>" + lastName + "</li>";
					html += "</ul>";
					return html;
				}

				function handleClick() {
					page_ul = document.getElementById(pagerId);
					//给UL添加事件
					document.addEventListener ?
						page_ul.addEventListener('click', handleUl) : page_ul.attachEvent('click', handleUl);

					function handleUl(e) {
						var e = e || window.event;
						var target = e.target || e.srcElement;

						if (target.tagName.toUpperCase() !== 'LI') return;
						//查找按钮是不是不可用的
						var index = findIndex(class2Array(target), [btn_dislabel, btn_selected]);
						if (index !== -1) {//如果是不可用的,则不响应点击
							return;
						}
						var page_val;//按钮选择后当前页的值
						//处理首页、上一页、下一页、尾页
						if (target.id === 'prev') {
							page_val = curPage - 1;
						} else if (target.id === 'next') {
							page_val = curPage + 1;
						} else if (target.id === 'first') {
							page_val = 1;
						} else if (target.id === 'last') {
							page_val = totalPage;
						} else {
							page_val = target.innerText;
						}
						curPage = parseInt(page_val);
						//每次选择要重新处理按钮
						handleBtn();
						//响应点击事件
						callback(curPage);
					}
				}

				function handleBtn() {
					//首页是否有效
					var first = page_ul.firstChild;
					if (curPage === 1) {
						handleClass(first, btn_dislabel, 'add');
					} else {
						handleClass(first, btn_dislabel, 'del');
					}
					//前一页按钮是否有效
					var prev = first.nextSibling;
					if (curPage === 1) {
						handleClass(prev, btn_dislabel, 'add');
					} else {
						handleClass(prev, btn_dislabel, 'del');
					}
					//nav_rela
					if (curPage === 1) {
						leftCount = 0;
					} else {
						nav_rela = curPage - nav_mid;
						leftCount = (leftCount + nav_rela) > 0 ? (leftCount + nav_rela) : 0;
						nav_mid += nav_rela;
					}
					if (curPage === totalPage) {
						rightCount = 0;
					} else {
						rightCount = totalPage - nav_count - leftCount;//右边隐藏节点数
					}

					//选择当前页
					for (var i = 1; i <= totalPage; i++) {
						var page = (i + 1);
						if (i == curPage) {//选择当前页
							if (curPage === 1 || curPage === totalPage) {
								handleClass(page_ul.childNodes[page], btn_hide, 'del');
							}
							handleClass(page_ul.childNodes[page], btn_selected, 'add');
						} else {
							if (leftCount <= 0 || rightCount <= 0) {//左右隐藏节点或者为0的时候,要另外处理
								if (leftCount <= 0) {
									if (i <= nav_count) {
										handleClass(page_ul.childNodes[page], btn_hide, 'del');
									} else {
										handleClass(page_ul.childNodes[page], btn_hide, 'add');
									}
								}
								if (rightCount <= 0) {
									if (i > totalPage - nav_count) {
										handleClass(page_ul.childNodes[page], btn_hide, 'del');
									} else {
										handleClass(page_ul.childNodes[page], btn_hide, 'add');
									}
								}
							} else {
								if (i <= leftCount) {
									handleClass(page_ul.childNodes[page], btn_hide, 'add');
								} else if (i > leftCount + nav_count) {
									handleClass(page_ul.childNodes[page], btn_hide, 'add');
								} else if (i <= (leftCount + nav_count)) {
									handleClass(page_ul.childNodes[page], btn_hide, 'del');
								}
							}
							handleClass(page_ul.childNodes[page], btn_selected, 'del');
						}
					}

					//最后一页按钮是否有效
					var last = page_ul.lastChild;
					if (curPage === totalPage || totalPage === 0) {
						handleClass(last, btn_dislabel, 'add');
					} else {
						handleClass(last, btn_dislabel, 'del');
					}
					//下一页按钮是否有效
					var next = last.previousSibling;
					if (curPage === totalPage || totalPage === 0) {
						handleClass(next, btn_dislabel, 'add');
					} else {
						handleClass(next, btn_dislabel, 'del');
					}

				}
				//将元素el的class转换成数组
				function class2Array(el) {
					var oldClass = el.className;
					if (!oldClass) return [];
					return oldClass.split(" ");
				}
				//添加或者删除当前el元素的指定class
				function handleClass(el, className, type) {
					var arr = class2Array(el);
					var index = findIndex(arr, className);

					if (type === 'add') {//添加
						if (index === -1) {
							arr.push(className);
						}
					} else {
						if (index !== -1) {//删除某个元素
							arr.splice(index, 1);
						}
					}

					el.className = arr.join(" ");
				}
				//根据传入的clas名来查到在数组中的下标
				function findIndex(arr, c) {
					if (c instanceof Array) {
						for (var i = 0; i < c.length; i++) {
							var num = findOnceIndex(arr, c[i]);
							if (num !== -1) {
								return num;
							}
						}
					} else {
						return findOnceIndex(arr, c);
					}
					return -1;
				}

				function findOnceIndex(arr, c) {
					for (var i = 0; i < arr.length; i++) {
						if (arr[i] === c) {
							return i;
						}
					}
					return -1;
				}
			}



			// var data = {
			// 	categoryId: '82efba2e6b0442f48a10c0f23b17e260',
			// 	pageSize: 6,
			// 	pageNo: pageNo,
			// }
			function getdata() {
				$.ajax({
					type: "POST",
					url: $.url('f/newsCenter/ajax_article_list'),
					data: data,
					success: function (res) {
						console.log(res);
						if (res.state == 1) {
							//院系
							
							var yxlist = res.data.page.list

							//console.log(yxlist);
							var yxstr = ``
							var zbliststr = ``
							for (var i = 0; i < yxlist.length; i++) {
								if (yxlist[i].subtitle == '') {
									zbliststr += `<li class="clear">
									<img src="${yxlist[i].imageSrc != '' ? yxlist[i].imageSrc : '../images/cms/index/img2.png'}" alt="" class="img">
									<div class="desc">
										<div class="tit">${yxlist[i].title}</div>
										<div class="bottom">
											<div class="time"><span>${new Date(yxlist[i].releaseDate).getFullYear()}</span>-<span>${new Date(yxlist[i].releaseDate).getMonth() + 1}</span>-<span>${new Date(yxlist[i].releaseDate).getDate()}</span>  <span>${new Date(yxlist[i].releaseDate).getHours()}</span>:<span>${new Date(yxlist[i].releaseDate).getMinutes()}</span></div>
											
										</div>
										<div class="btn"><a
											href="${yxlist[i].link
										}"
											style="width:100%;height: 100%;display: block;" target='_blank'></a></div>
									</div>
									
								</li>`
								}

							}

							$('#zblist').html(zbliststr)
							
						}
					}
				})
			}
			

		</script>