如何在WordPress/HTML中实现循环式上/下一页按钮(无需PHP)
纯JavaScript实现循环分页与全页面菜单
实现思路
- 从当前页面URL中提取页码(比如从
x_3.html中解析出数字3) - 基于当前页码计算循环逻辑的上/下一页(最后一页下跳至第一页,第一页上跳至最后一页)
- 动态绑定按钮跳转事件
- 自动生成包含所有50个页面的菜单列表
完整代码
直接把这段代码复制到每个x_*.html页面的<body>末尾即可:
<!-- 分页按钮容器 --> <div class="pagination-buttons"> <button id="prevBtn">上一页</button> <button id="nextBtn">下一页</button> </div> <!-- 全页面菜单容器 --> <div class="page-menu"> <h3>所有页面</h3> <div id="menuList"></div> </div> <script> // 配置参数 const totalPages = 50; const pagePrefix = 'x_'; // 获取当前页面的页码 function getCurrentPage() { const fileName = window.location.pathname.split('/').pop(); const match = fileName.match(/x_(\d+)\.html/); return match ? parseInt(match[1], 10) : 1; } // 生成指定页码的页面链接 function getPageUrl(pageNum) { return `${pagePrefix}${pageNum}.html`; } // 初始化上下页按钮 function initPagination() { const currentPage = getCurrentPage(); const prevBtn = document.getElementById('prevBtn'); const nextBtn = document.getElementById('nextBtn'); // 计算上一页:当前是第一页则跳最后一页,否则减1 const prevPage = currentPage === 1 ? totalPages : currentPage - 1; // 计算下一页:当前是最后一页则跳第一页,否则加1 const nextPage = currentPage === totalPages ? 1 : currentPage + 1; prevBtn.addEventListener('click', () => { window.location.href = getPageUrl(prevPage); }); nextBtn.addEventListener('click', () => { window.location.href = getPageUrl(nextPage); }); } // 初始化全页面菜单 function initMenu() { const menuList = document.getElementById('menuList'); for (let i = 1; i <= totalPages; i++) { const link = document.createElement('a'); link.href = getPageUrl(i); link.textContent = `页面 ${i}`; // 当前页面链接高亮显示 if (i === getCurrentPage()) { link.style.fontWeight = 'bold'; link.style.color = '#007bff'; } menuList.appendChild(link); menuList.appendChild(document.createElement('br')); } } // 页面加载完成后执行初始化 window.addEventListener('load', () => { initPagination(); initMenu(); }); </script> <!-- 可选基础样式 --> <style> .pagination-buttons { margin: 20px 0; } .pagination-buttons button { padding: 8px 16px; margin-right: 10px; cursor: pointer; } .page-menu { margin-top: 30px; } .page-menu a { text-decoration: none; margin-right: 5px; } </style>
使用说明
- 将代码复制到所有
x_1.html至x_50.html页面中,无需修改参数(除非你调整了页面命名规则或总页数) - 打开任意页面,点击「上一页」「下一页」即可实现循环跳转
- 页面菜单会自动生成所有页面的链接,当前页面链接会高亮标记
内容的提问来源于stack exchange,提问作者Steven
相关产品推荐
相关产品推荐

