萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現 JSON 數據分頁:零依賴、可復用的分頁組件

核心邏輯

分頁本質:總條數 ÷ 每頁條數 = 總頁數,根據當前頁碼計算 `start = (page-1)*pageSize`,截取 `data.slice(start, start+pageSize)` 渲染。

完整可復用分頁類

class JsonPaginator {
  constructor(options = {}) {
    this.data = options.data || [];           // 完整數據陣列
    this.pageSize = options.pageSize || 10;   // 每頁條數
    this.container = document.getElementById(options.containerId); // 表格 tbody
    this.paginationEl = document.getElementById(options.paginationId); // 分頁條容器
    this.renderRow = options.renderRow || this._defaultRenderRow; // 行渲染函數
    this.currentPage = 1;
    this.totalPages = Math.ceil(this.data.length / this.pageSize);
    
    this._bindEvents();
    this.render();
  }
  
  _bindEvents() {
    // 事件委託處理分頁按鈕
    this.paginationEl.addEventListener('click', (e) => {
      const btn = e.target.closest('button[data-page]');
      if (!btn) return;
      const page = parseInt(btn.dataset.page, 10);
      this.goTo(page);
    });
  }
  
  _defaultRenderRow(item, index) {
    const tr = document.createElement('tr');
    tr.innerHTML = Object.values(item).map(v => `${v}`).join('');
    return tr;
  }
  
  getPageData(page) {
    const start = (page - 1) * this.pageSize;
    return this.data.slice(start, start + this.pageSize);
  }
  
  render() {
    // 1. 渲染表格數據
    const pageData = this.getPageData(this.currentPage);
    const fragment = document.createDocumentFragment();
    pageData.forEach((item, i) => {
      fragment.appendChild(this.renderRow(item, (this.currentPage - 1) * this.pageSize + i));
    });
    this.container.innerHTML = '';
    this.container.appendChild(fragment);
    
    // 2. 渲染分頁條
    this._renderPagination();
  }
  
  _renderPagination() {
    const maxButtons = 5; // 最多顯示頁碼按鈕數
    let html = '';
    
    // 上一頁
    html += ``;
    
    // 頁碼範圍計算
    let startPage = Math.max(1, this.currentPage - Math.floor(maxButtons / 2));
    let endPage = Math.min(this.totalPages, startPage + maxButtons - 1);
    if (endPage - startPage + 1 < maxButtons) {
      startPage = Math.max(1, endPage - maxButtons + 1);
    }
    
    for (let p = startPage; p <= endPage; p++) {
      html += ``;
    }
    
    // 下一頁
    html += ``;
    
    // 頁面信息
    html += `第 ${this.currentPage} / ${this.totalPages} 頁,共 ${this.data.length} 條`;
    
    this.paginationEl.innerHTML = html;
  }
  
  goTo(page) {
    if (page < 1 || page > this.totalPages || page === this.currentPage) return;
    this.currentPage = page;
    this.render();
  }
  
  // 公開方法:更新數據並重置到第 1 頁
  setData(newData) {
    this.data = newData;
    this.totalPages = Math.ceil(this.data.length / this.pageSize);
    this.currentPage = 1;
    this.render();
  }
}

// 初始化示例
const rawData = {
  "code": 1,
  "list": [
    {"category1_id":"1","category1_name":"酒水飲料","category1_intro":"清爽可口的酒水飲料","category1_images":"https://example.com/1.jpg"},
    {"category1_id":"2","category1_name":"米面糧油","category1_intro":"家庭必備","category1_images":"https://example.com/2.jpg"},
    {"category1_id":"3","category1_name":"美容洗護","category1_intro":"護膚必備","category1_images":"https://example.com/3.jpg"},
    {"category1_id":"4","category1_name":"清潔洗漱","category1_intro":"給您一個乾淨的生活環境","category1_images":"https://example.com/4.jpg"},
    {"category1_id":"5","category1_name":"生活用品","category1_intro":"家庭必備","category1_images":"https://example.com/5.jpg"},
    {"category1_id":"6","category1_name":"休閒食品","category1_intro":"好吃美味","category1_images":"https://example.com/6.jpg"}
  ]
};

document.addEventListener('DOMContentLoaded', () => {
  new JsonPaginator({
    data: rawData.list,
    pageSize: 2,
    containerId: 'tableBody',
    paginationId: 'pagination',
    renderRow: (item) => {
      const tr = document.createElement('tr');
      tr.innerHTML = `
        ${item.category1_id}
        ${item.category1_name}
        ${item.category1_intro}
        
      `;
      return tr;
    }
  });
});

HTML 模板

<table border="1" id="dataTable">
  <thead>
    <tr>
      <th>ID</th><th>名稱</th><th>介紹</th><th>圖片</th>
    </tr>
  </thead>
  <tbody id="tableBody"></tbody>
</table>
<div id="pagination" style="margin-top:10px; text-align:center;"></div>

<style>
#pagination button { margin: 0 4px; padding: 4px 10px; cursor: pointer; }
#pagination button:disabled { opacity: 0.5; cursor: not-allowed; }
#pagination button.active { background: #007bff; color: white; border-color: #007bff; }
.page-info { margin-left: 15px; color: #666; }
</style>

進階擴展

  • 跳頁輸入框:在分頁條添加 `` + 確定按鈕
  • 每頁條數切換:`