JavaScript 实现表格数据分页显示

2025-01-10 18:20:12   小编

JavaScript 实现表格数据分页显示

在网页开发中,当面对大量表格数据时,一次性全部展示会导致页面加载缓慢,用户体验不佳。这时,分页显示成为优化数据展示的有效手段。而借助 JavaScript,我们能够轻松实现表格数据的分页功能。

搭建基本的 HTML 结构。创建一个包含表格的页面,表格里填充好要展示的数据。例如:

<table id="dataTable">
  <thead>
    <tr>
      <th>序号</th>
      <th>姓名</th>
      <th>年龄</th>
    </tr>
  </thead>
  <tbody id="dataBody">
    <!-- 动态填充数据 -->
  </tbody>
</table>
<div id="pagination"></div>

上述代码创建了一个简单的表格和用于显示分页按钮的区域。

接着,使用 JavaScript 来处理数据和分页逻辑。假设我们有一个包含所有数据的数组:

const data = [
  { id: 1, name: '张三', age: 25 },
  { id: 2, name: '李四', age: 30 },
  // 更多数据
];

定义分页相关变量,如每页显示的记录数和当前页码:

const recordsPerPage = 10;
let currentPage = 1;

编写函数来渲染表格数据:

function renderTable() {
  const dataBody = document.getElementById('dataBody');
  dataBody.innerHTML = '';
  const startIndex = (currentPage - 1) * recordsPerPage;
  const endIndex = startIndex + recordsPerPage;
  const currentData = data.slice(startIndex, endIndex);
  currentData.forEach((item, index) => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${startIndex + index + 1}</td>
      <td>${item.name}</td>
      <td>${item.age}</td>
    `;
    dataBody.appendChild(row);
  });
}

再编写函数来渲染分页按钮:

function renderPagination() {
  const pagination = document.getElementById('pagination');
  pagination.innerHTML = '';
  const totalPages = Math.ceil(data.length / recordsPerPage);
  for (let i = 1; i <= totalPages; i++) {
    const button = document.createElement('button');
    button.textContent = i;
    button.addEventListener('click', () => {
      currentPage = i;
      renderTable();
      renderPagination();
    });
    pagination.appendChild(button);
  }
}

最后,在页面加载完成后调用渲染函数:

window.addEventListener('load', () => {
  renderTable();
  renderPagination();
});

通过上述步骤,利用 JavaScript 实现了表格数据的分页显示。不仅提升了页面性能,还为用户带来更流畅的浏览体验。无论是小型项目还是大型企业级应用,这种分页技术都能有效优化数据展示,值得开发者熟练掌握和应用。

TAGS: 表格数据 JavaScript 分页显示 数据显示

欢迎使用万千站长工具!

Welcome to www.zzTool.com