首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

表格分页js代码怎么写

以下是一个简单的表格分页 JavaScript 代码示例:

代码语言:txt
复制
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>表格分页示例</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    table,
    th,
    td {
      border: 1px solid black;
    }

    .pagination {
      margin-top: 10px;
      text-align: center;
    }

    .pagination button {
      margin: 0 5px;
    }
  </style>
</head>

<body>
  <table id="myTable">
    <thead>
      <tr>
        <th>ID</th>
        <th>名称</th>
      </tr>
    </thead>
    <tbody>
      <!-- 表格数据将通过 JavaScript 动态生成 -->
    </tbody>
  </table>
  <div class="pagination">
    <!-- 分页按钮将通过 JavaScript 动态生成 -->
  </div>

  <script>
    const data = [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      // ... 更多数据
    ];
    const itemsPerPage = 10; // 每页显示的条目数
    let currentPage = 1; // 当前页码

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

      const tbody = document.querySelector('#myTable tbody');
      tbody.innerHTML = '';

      pageData.forEach(item => {
        const row = document.createElement('tr');
        const idCell = document.createElement('td');
        idCell.textContent = item.id;
        const nameCell = document.createElement('td');
        nameCell.textContent = item.name;
        row.appendChild(idCell);
        row.appendChild(nameCell);
        tbody.appendChild(row);
      });
    }

    function renderPagination() {
      const totalPages = Math.ceil(data.length / itemsPerPage);
      const pagination = document.querySelector('.pagination');
      pagination.innerHTML = '';

      for (let i = 1; i <= totalPages; i++) {
        const button = document.createElement('button');
        button.textContent = i;
        button.addEventListener('click', () => {
          currentPage = i;
          renderTable(currentPage);
          renderPagination();
        });
        if (i === currentPage) {
          button.disabled = true;
        }
        pagination.appendChild(button);
      }
    }

    renderTable(currentPage);
    renderPagination();
  </script>
</body>

</html>

基础概念:分页是将大量的数据按照一定的规则分成多个页面进行展示,以提高用户体验和数据加载效率。

优势:

  1. 提高页面加载速度,避免一次性加载大量数据导致页面卡顿。
  2. 方便用户查看和管理大量数据。

类型:

  1. 前端分页:在客户端进行数据的分页处理。
  2. 后端分页:在服务器端进行数据的分页处理,客户端只负责展示。

应用场景:

  1. 数据库查询结果的分页展示。
  2. 大型列表或表格的数据展示。

常见问题及解决方法:

  1. 分页数据不准确:确保计算总页数和每页数据的逻辑正确。
  2. 分页按钮状态错误:在切换页面时,及时更新当前页码并重新渲染分页按钮的状态。

希望这个示例对你有所帮助,如有其他需求,请继续提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券