当前位置:首页 > JavaScript

js实现分页

2026-01-08 12:21:13JavaScript

实现分页的基本思路

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

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

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

js实现分页

// 示例数据
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获取分页数据:

js实现分页

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实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

vue 分页的实现

vue 分页的实现

分页组件实现 使用Vue实现分页功能通常需要结合后端API和前端组件。以下是一种常见的实现方式: 模板部分 <template> <div class="pagina…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js画图实现

js画图实现

使用Canvas API绘制图形 Canvas是HTML5提供的绘图API,通过JavaScript操作Canvas元素可以绘制各种图形。以下是一个简单的示例: <canvas id="myC…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码 funct…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…