当前位置:首页 > JavaScript

js实现分页代码

2026-03-01 02:09:00JavaScript

实现分页功能的基本思路

分页功能通常需要处理数据分割、页码计算和UI交互。核心逻辑包括计算总页数、当前页数据切片以及页码按钮生成。

js实现分页代码

基础分页实现代码示例

// 模拟数据
const allData = Array.from({length: 100}, (_, i) => `Item ${i + 1}`);

function paginate(data, currentPage = 1, itemsPerPage = 10) {
    const totalPages = Math.ceil(data.length / itemsPerPage);
    const startIdx = (currentPage - 1) * itemsPerPage;
    const endIdx = startIdx + itemsPerPage;
    const pageData = data.slice(startIdx, endIdx);

    return {
        currentPage,
        totalPages,
        pageData,
        hasNext: currentPage < totalPages,
        hasPrev: currentPage > 1
    };
}

// 使用示例
const result = paginate(allData, 2);
console.log(result);

分页UI组件实现

class Pagination {
    constructor(containerId, options) {
        this.container = document.getElementById(containerId);
        this.data = options.data;
        this.itemsPerPage = options.itemsPerPage || 10;
        this.currentPage = 1;
        this.render();
    }

    render() {
        const { pageData, totalPages } = paginate(this.data, this.currentPage, this.itemsPerPage);

        // 渲染数据列表
        const listHtml = pageData.map(item => `<li>${item}</li>`).join('');

        // 渲染页码按钮
        let pageButtons = '';
        for (let i = 1; i <= totalPages; i++) {
            pageButtons += `<button class="${i === this.currentPage ? 'active' : ''}" 
                                data-page="${i}">${i}</button>`;
        }

        this.container.innerHTML = `
            <ul class="data-list">${listHtml}</ul>
            <div class="pagination-controls">
                <button class="prev" ${this.currentPage === 1 ? 'disabled' : ''}>Previous</button>
                ${pageButtons}
                <button class="next" ${this.currentPage === totalPages ? 'disabled' : ''}>Next</button>
            </div>
        `;

        this.addEventListeners();
    }

    addEventListeners() {
        this.container.addEventListener('click', (e) => {
            if (e.target.classList.contains('prev')) {
                this.currentPage--;
                this.render();
            } else if (e.target.classList.contains('next')) {
                this.currentPage++;
                this.render();
            } else if (e.target.hasAttribute('data-page')) {
                this.currentPage = parseInt(e.target.getAttribute('data-page'));
                this.render();
            }
        });
    }
}

// 使用示例
const pagination = new Pagination('pagination-container', {
    data: allData,
    itemsPerPage: 5
});

服务器端分页实现

当数据量很大时,通常需要结合AJAX实现服务器端分页:

js实现分页代码

async function fetchPaginatedData(page = 1, size = 10) {
    const response = await fetch(`/api/data?page=${page}&size=${size}`);
    return await response.json();
}

// 使用示例
fetchPaginatedData(2).then(data => {
    console.log(data.items); // 当前页数据
    console.log(data.totalPages); // 总页数
});

分页样式建议

.pagination-controls {
    display: flex;
    gap: 5px;
    margin-top: 20px;
}

.pagination-controls button {
    padding: 5px 10px;
    border: 1px solid #ddd;
    background: #fff;
    cursor: pointer;
}

.pagination-controls button.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.pagination-controls button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

高级分页功能扩展

对于更复杂的需求,可以考虑实现以下功能:

  • 动态调整每页显示数量
  • 跳转到指定页码的输入框
  • 显示总记录数和当前显示范围
  • 响应式分页控件(移动端优化)
  • 分页缓存策略
  • 无限滚动分页替代方案

标签: 分页代码
分享给朋友:

相关文章

h5实现响应式代码

h5实现响应式代码

响应式设计基础 HTML5实现响应式设计主要通过媒体查询(Media Queries)、弹性布局(Flexbox)、网格布局(Grid)和视口设置(Viewport Meta Tag)等技术。核心目标…

vue加载实现分页

vue加载实现分页

Vue 实现分页加载的方法 使用 Element UI 的分页组件 安装 Element UI 后,可以直接使用其分页组件。在模板中添加分页组件,并绑定相关事件和数据。 <template&g…

vue实现分页按钮

vue实现分页按钮

实现分页按钮的基本思路 在Vue中实现分页按钮通常需要结合计算属性、事件绑定和动态样式。核心逻辑包括计算总页数、生成页码数组、处理页码切换事件以及高亮当前页码。 基础实现代码示例 <templ…

vue 实现简单分页

vue 实现简单分页

Vue 实现简单分页的方法 基础分页组件实现 创建一个基础分页组件,包含页码按钮和翻页功能。以下是一个基于 Vue 3 的示例: <template> <div class="…

vue iview实现分页

vue iview实现分页

Vue + iView 实现分页 在 Vue 项目中结合 iView 组件库实现分页功能,可以通过 Page 组件轻松完成。以下是具体实现方法: 安装 iView 确保项目中已安装 iView,可以…

vue实现代码插件

vue实现代码插件

Vue 实现代码插件的方法 使用第三方库(如 Prism.js 或 Highlight.js) 安装 Prism.js 或 Highlight.js 库,这些库专门用于代码高亮显示。在 Vue 项目中…