jquery无刷新分页
数据json必须是本地
XML/HTML Code
- <!-- news数据 -->
- <div class="container"></div>
- <!-- 分页器 -->
- <div class="pagination"></div>
JavaScript Code
- $(function () {
- axios({
- url: 'js/news.json'
- }).then(result => {
- const pageSize = 5; // 每页显示的数量
- let currentPage = 1; // 当前页码
- // 生成分页HTML
- function newPageHTML(total, pageSize, currentPage) {
- const totalPages = Math.ceil(total / pageSize);
- let paginationHTML = '<a href="##" class="a">首页</a><a href="##" class="a previousPage">上一页</a>';
- const maxList = 10;
- let startPage = Math.max(currentPage - Math.floor(maxList / 2), 1);
- let endPage = Math.min(startPage + maxList - 1, totalPages);
- if (endPage - startPage < maxList - 1) {
- startPage = Math.max(endPage - maxList + 1, 1);
- }
- for (let i = startPage; i <= endPage; i++) {
- paginationHTML += `<a href='##' class="${i === currentPage ? 'active ' : ''}a">${i}</a>`;
- }
- paginationHTML += '<a href="##" class="a">尾页</a><a href="##" class="a nextPage">下一页</a>';
- return paginationHTML;
- }
- // 根据页码显示新闻列表
- function newNews(page) {
- currentPage = page;
- const startIndex = (currentPage - 1) * pageSize;
- const endIndex = Math.min(startIndex + pageSize - 1, result.data.length);
- const dataList = result.data.slice(startIndex, endIndex).map(item => `
- <div class='box'>
- <a href="javascript:;">
- <div class='aBox'>
- <img src="${item.images}" alt="">
- </div>
- </a>
- <div class="right">
- <h2>${item.title}</h2>
- <span>${item.time}</span>
- <p>${item.paragraph}</p>
- </div>
- </div>
- `).join("");
- $(".container").html(dataList);
- // 生成分页HTML并更新页面
- const paginationHTML = newPageHTML(result.data.length, pageSize, currentPage);
- $(".pagination").html(paginationHTML);
- alert(".previousPage", 1, '已经是第一页拉~', true);
- alert(".nextPage", Math.ceil(result.data.length / pageSize), '已经是最后一页拉~', false);
- }
- function alert(el, num, alertMessage, isSuccess) {
- $(document).on("click", el, function () {
- if (currentPage === num) {
- // myAlert(isSuccess, alertMessage);
- console.log(currentPage);
- }
- });
- }
- // 初始化分页和新闻列表
- newNews(currentPage);
- // 点击页码链接切换页码
- $(".pagination").on("click", ".a", function () {
- const page = $(this).text();
- currentPage = page === "首页" ? 1 :
- page === "尾页" ? Math.ceil(result.data.length / pageSize) :
- page === "上一页" ? Math.max(currentPage - 1, 1) :
- page === "下一页" ? Math.min(currentPage + 1, Math.ceil(result.data.length / pageSize)) :
- parseInt(page);
- newNews(currentPage);
- });
- });
- });
原文地址:http://www.freejs.net/article_fenye_946.html