当前位置:首页 > 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);

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

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

相关文章

vue router实现分页

vue router实现分页

使用 Vue Router 实现分页 在 Vue.js 项目中,可以通过 Vue Router 结合分页组件实现分页功能。以下是实现分页的几种方法: 使用路由参数传递页码 在路由配置中定义一个动态参…

php实现文件下载代码

php实现文件下载代码

实现文件下载的基本方法 使用PHP实现文件下载的核心是通过设置HTTP头部信息,强制浏览器触发下载行为而非直接显示文件内容。 $file_path = 'path/to/your/file.ext'…

vue 实现数据分页

vue 实现数据分页

实现数据分页的基本思路 在Vue中实现数据分页通常需要结合前端分页逻辑和后端API支持。前端分页适合数据量较小的情况,后端分页适合大数据量场景。 前端分页实现 创建一个计算属性来分割当前页数据:…

用vue实现分页

用vue实现分页

使用Vue实现分页功能 分页是Web应用中常见的功能,可以通过Vue结合计算属性和事件处理实现。以下是实现分页的核心步骤: 数据准备 定义数据模型,包括当前页码、每页显示数量和总数据列表: dat…

vue实现前端分页

vue实现前端分页

实现前端分页的方法 在Vue中实现前端分页通常需要结合数据截取和分页组件。以下是常见的实现方式: 基础实现方案 数据准备 定义总数据数组和分页相关变量: data() { return {…

vue实现分页缩进

vue实现分页缩进

vue实现分页缩进的方法 使用v-for和计算属性实现分页 通过计算属性对数据进行分页处理,结合v-for渲染分页数据。计算属性根据当前页码和每页显示数量对原始数据进行切片。 computed: {…