当前位置:首页 > JavaScript

js实现分页

2026-01-08 12:21:13JavaScript

实现分页的基本思路

分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。

前端分页实现(静态数据)

假设已有全部数据,仅需前端分页展示:

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

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

  return {
    currentPage,
    perPage,
    totalPages,
    data: paginatedData
  };
}

// 使用示例
const result = paginate(allData, 2);
console.log(result.data); // 显示第2页的10条数据

动态分页控件实现

创建可交互的分页UI组件:

class Pagination {
  constructor({ totalItems, perPage = 10, currentPage = 1 }) {
    this.totalItems = totalItems;
    this.perPage = perPage;
    this.currentPage = currentPage;
    this.totalPages = Math.ceil(totalItems / perPage);
  }

  render(container) {
    container.innerHTML = '';

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

    // 页码按钮
    for (let i = 1; i <= this.totalPages; i++) {
      const pageBtn = document.createElement('button');
      pageBtn.textContent = i;
      if (i === this.currentPage) {
        pageBtn.classList.add('active');
      }
      pageBtn.addEventListener('click', () => this.goToPage(i));
      container.appendChild(pageBtn);
    }

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

  goToPage(page) {
    this.currentPage = Math.max(1, Math.min(page, this.totalPages));
    this.onPageChange(this.currentPage);
    this.render(document.getElementById('pagination-container'));
  }

  onPageChange() {} // 由使用者重写
}

// 使用示例
const pagination = new Pagination({ totalItems: 100 });
pagination.onPageChange = (page) => {
  console.log(`当前页码: ${page}`);
  // 这里可以发起API请求或更新DOM
};
pagination.render(document.getElementById('pagination-container'));

结合API的分页实现

实际项目中常需要从后端API获取分页数据:

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

    return {
      data,
      currentPage: page,
      totalPages: Math.ceil(total / perPage)
    };
  } catch (error) {
    console.error('获取数据失败:', error);
    return { data: [], currentPage: 1, totalPages: 1 };
  }
}

// 使用示例
fetchPaginatedData(2).then(({ data }) => {
  console.log('第2页数据:', data);
});

分页样式优化建议

添加基础CSS样式提升用户体验:

.pagination-container button {
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
}

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

.pagination-container button:hover:not(.active) {
  background: #f0f0f0;
}

性能优化技巧

对于大数据量场景:

  • 使用虚拟滚动代替传统分页
  • 实现无限滚动加载
  • 添加缓存机制避免重复请求
  • 考虑预加载相邻页面的数据

以上实现方案可根据具体需求组合使用,静态数据分页适合小型应用,API分页适合数据量大的场景,动态分页控件可复用性最高。

js实现分页

标签: 分页js
分享给朋友:

相关文章

vue搜索过后实现分页

vue搜索过后实现分页

Vue 实现搜索后分页功能 数据绑定与搜索逻辑 在 Vue 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPag…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用第三方库(如 Element UI) Element UI 提供了现成的分页组件 el-pagination,适合快速集成。 安装 Element UI: npm ins…

vue  实现分页

vue 实现分页

实现分页的基本思路 在Vue中实现分页通常需要结合后端API返回的数据和前端的分页组件。分页的核心逻辑包括计算总页数、处理当前页码变化以及触发数据请求。 分页组件示例 使用Element UI的分…

vue实现分页条数

vue实现分页条数

实现分页条数的方法 在Vue中实现分页条数功能,通常需要结合分页组件和数据请求逻辑。以下是几种常见的实现方式: 使用Element UI的分页组件 Element UI提供了现成的分页组件,可以快…

php实现分页

php实现分页

PHP实现分页的基本方法 使用原生PHP实现分页功能需要结合数据库查询和HTML展示。以下是核心实现步骤: 数据库查询与分页逻辑 // 连接数据库 $conn = new mysqli('loca…