You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS+EJS实现表格分页:添加上下页按钮及每页5行展示

Alright, let's get your EJS table pagination sorted out. Since you're using Node.js with EJS, here's a straightforward, working solution that adds "Previous" and "Next" buttons while showing 5 records per page:

Step 1: Backend Pagination Logic (Node.js/Express)

First, we'll handle pagination parameters in your route, slice your JSON data to get only the records for the current page, and pass necessary pagination metadata to EJS.

const express = require('express');
const router = express.Router();
const fs = require('fs').promises;

router.get('/', async (req, res) => {
  // Read your JSON data file
  const rawJson = await fs.readFile('./path/to/your/data.json', 'utf8');
  const data = JSON.parse(rawJson);
  const allRecords = data.s_history;

  // Pagination configuration
  const itemsPerPage = 5;
  const currentPage = parseInt(req.query.page) || 1; // Default to page 1 if no query param
  const totalItems = allRecords.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);

  // Ensure current page is within valid bounds
  const validPage = Math.max(1, Math.min(currentPage, totalPages));
  
  // Calculate slice indices for the current page
  const startIndex = (validPage - 1) * itemsPerPage;
  const paginatedRecords = allRecords.slice(startIndex, startIndex + itemsPerPage);

  // Pass data to EJS template
  res.render('your-template-name', {
    paginatedRecords,
    currentPage: validPage,
    totalPages
  });
});

module.exports = router;

Step 2: Update EJS Table to Render Paginated Data

Replace your existing <tbody> code with this to loop through only the records for the current page:

<tbody>
  <% paginatedRecords.forEach((record) => { %>
    <tr>
      <td>
        <%= record.date %>
        <span style="display: block;font-size:10pt;"><%= record.time %></span>
      </td>
      <!-- Add other table cells here if needed -->
    </tr>
  <% }) %>
</tbody>

Step 3: Add Pagination Buttons

Place this code below your table to render "Previous" and "Next" buttons, along with optional page number indicators:

<div style="margin-top: 16px; display: flex; gap: 8px; align-items: center;">
  <!-- Previous Page Button -->
  <% if (currentPage > 1) { %>
    <a href="/?page=<%= currentPage - 1 %>" style="padding: 4px 12px; border: 1px solid #ccc; text-decoration: none; color: #333;">上一页</a>
  <% } else { %>
    <span style="padding: 4px 12px; border: 1px solid #ccc; color: #999; cursor: not-allowed;">上一页</span>
  <% } %>

  <!-- Optional Page Number Links -->
  <% for (let i = 1; i <= totalPages; i++) { %>
    <% if (i === currentPage) { %>
      <span style="font-weight: bold; padding: 0 8px;"><%= i %></span>
    <% } else { %>
      <a href="/?page=<%= i %>" style="padding: 0 8px; text-decoration: none; color: #333;"><%= i %></a>
    <% } %>
  <% } %>

  <!-- Next Page Button -->
  <% if (currentPage < totalPages) { %>
    <a href="/?page=<%= currentPage + 1 %>" style="padding: 4px 12px; border: 1px solid #ccc; text-decoration: none; color: #333;">下一页</a>
  <% } else { %>
    <span style="padding: 4px 12px; border: 1px solid #ccc; color: #999; cursor: not-allowed;">下一页</span>
  <% } %>
</div>

Key Notes:

  • We validate the page query parameter to prevent invalid values (like 0 or a number larger than total pages)
  • The slice() method safely extracts only the records needed for the current page from your JSON array
  • Buttons are disabled (greyed out) when they can't be used (e.g., "Previous" on page 1)

内容的提问来源于stack exchange,提问作者dutchkillsg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:13:21