当前位置:首页 > JavaScript

js实现分页代码

2026-01-30 11:03:39JavaScript

分页实现方法

前端分页(纯JavaScript)

适用于数据量较小的情况,直接在客户端完成分页逻辑。

js实现分页代码

function paginate(data, itemsPerPage, currentPage) {
  const startIndex = (currentPage - 1) * itemsPerPage;
  return data.slice(startIndex, startIndex + itemsPerPage);
}

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

// 使用示例
const pageSize = 10;
const currentPage = 3;
const pageData = paginate(allData, pageSize, currentPage);

console.log(pageData); // 显示第3页的10条数据

后端分页(AJAX请求)

适用于大数据量场景,需要与后端API配合。

js实现分页代码

async function fetchPaginatedData(page, size) {
  try {
    const response = await fetch(`/api/data?page=${page}&size=${size}`);
    const result = await response.json();
    return {
      data: result.items,
      total: result.totalCount
    };
  } catch (error) {
    console.error('Error fetching data:', error);
    return { data: [], total: 0 };
  }
}

// 使用示例
const currentPage = 1;
const pageSize = 10;

fetchPaginatedData(currentPage, pageSize)
  .then(({data, total}) => {
    console.log('Fetched data:', data);
    renderPaginationControls(total, pageSize);
  });

function renderPaginationControls(totalItems, itemsPerPage) {
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  // 渲染分页UI逻辑
}

完整分页组件实现

包含分页逻辑和UI控制的完整示例:

class Pagination {
  constructor({ data = [], pageSize = 10, currentPage = 1 }) {
    this.data = data;
    this.pageSize = pageSize;
    this.currentPage = currentPage;
    this.totalPages = Math.ceil(data.length / pageSize);
  }

  getPaginatedData() {
    const start = (this.currentPage - 1) * this.pageSize;
    const end = start + this.pageSize;
    return this.data.slice(start, end);
  }

  nextPage() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
    }
    return this.getPaginatedData();
  }

  prevPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
    }
    return this.getPaginatedData();
  }

  goToPage(page) {
    if (page >= 1 && page <= this.totalPages) {
      this.currentPage = page;
    }
    return this.getPaginatedData();
  }
}

// 使用示例
const paginator = new Pagination({
  data: Array.from({length: 50}, (_, i) => `Item ${i+1}`),
  pageSize: 5
});

console.log(paginator.getPaginatedData()); // 第1页
console.log(paginator.nextPage());         // 第2页
console.log(paginator.goToPage(3));        // 第3页

分页UI渲染

结合DOM操作的分页控件实现:

function renderPagination(data, containerId, itemsPerPage = 10) {
  const container = document.getElementById(containerId);
  const totalPages = Math.ceil(data.length / itemsPerPage);
  let currentPage = 1;

  function renderPage(page) {
    const start = (page - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const pageData = data.slice(start, end);

    // 清空容器并渲染当前页数据
    container.innerHTML = '';
    pageData.forEach(item => {
      const div = document.createElement('div');
      div.textContent = item;
      container.appendChild(div);
    });

    // 渲染分页控件
    renderPaginationControls();
  }

  function renderPaginationControls() {
    const controls = document.createElement('div');
    controls.className = 'pagination-controls';

    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.textContent = 'Previous';
    prevBtn.disabled = currentPage === 1;
    prevBtn.addEventListener('click', () => {
      if (currentPage > 1) {
        currentPage--;
        renderPage(currentPage);
      }
    });

    // 页码按钮
    const pages = document.createElement('div');
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = document.createElement('button');
      pageBtn.textContent = i;
      pageBtn.className = i === currentPage ? 'active' : '';
      pageBtn.addEventListener('click', () => {
        currentPage = i;
        renderPage(currentPage);
      });
      pages.appendChild(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.textContent = 'Next';
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.addEventListener('click', () => {
      if (currentPage < totalPages) {
        currentPage++;
        renderPage(currentPage);
      }
    });

    controls.appendChild(prevBtn);
    controls.appendChild(pages);
    controls.appendChild(nextBtn);
    container.appendChild(controls);
  }

  // 初始渲染
  renderPage(currentPage);
}

// 使用示例
const testData = Array.from({length: 35}, (_, i) => `Data Item ${i+1}`);
renderPagination(testData, 'data-container', 5);

这些实现涵盖了从简单数据分片到完整分页组件的不同场景,可以根据具体需求选择适合的方案或组合使用。

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

相关文章

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

网页表格制作css代码

网页表格制作css代码

基础表格样式 使用CSS为HTML表格添加基础样式,如边框、间距和背景色: table { width: 100%; border-collapse: collapse; margin:…

vue搜索过后实现分页

vue搜索过后实现分页

实现 Vue 搜索后分页的方法 数据绑定与搜索逻辑 在 Vue 组件中定义数据属性,包括原始数据列表、搜索关键词、分页相关参数: data() { return { originalLi…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…

js实现分页功能代码

js实现分页功能代码

分页功能实现方法 客户端分页(前端处理数据) 适用于数据量较小且已全部加载到前端的情况。 // 示例数据 const data = Array.from({length: 100}, (_, i)…