DIV CSS 佈局教程網

純前端表格翻頁:用 display 切換實作分頁瀏覽
編輯:關於JavaScript     

資料量不大、又不想為了翻頁而請後端撈資料時,可以把全部列都印在頁面上,再用 JavaScript 控制每一列的 display 來模擬分頁。這個範例還多做了一件事:用 Cookie 記住使用者目前在第幾頁,重新整理後仍停在原處。

核心參數與 Cookie 工具

<script type="text/javascript">
var record    = 4;    // 每頁顯示幾筆
var count     = 24;   // 總筆數
var pageTotal = ((count + record - 1) / record) | 0;   // 總頁數(無條件進位)
var pagenum   = 1;    // 目前頁碼

Cookie = {
    Set : function () {
        var name = arguments[0], value = escape(arguments[1]), days = 365, path = "/";
        if (arguments.length > 2) days = arguments[2];
        if (arguments.length > 3) path = arguments[3];
        with (new Date()) { setDate(getDate() + days); days = toUTCString(); }
        document.cookie = "{0}={1};expires={2};path={3}".format(name, value, days, path);
    },
    Get : function () {
        var returnValue = document.cookie.match(
            new RegExp("[\b\^;]?" + arguments[0] + "=([^;]*)(?=;|\b|$)", "i"));
        return returnValue ? unescape(returnValue[1]) : returnValue;
    }
};

String.prototype.format = function () {
    var tmpStr = this;
    for (var i = 0; i < arguments.length; i++) {
        tmpStr = tmpStr.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
    }
    return tmpStr;
};

// 從 Cookie 還原頁碼,並夾在合法範圍內
function coordinatePagenum(num) {
    if (num < 1) num = 1;
    else if (num > pageTotal) num = pageTotal;
    return num;
}

var saved = Cookie.Get("pagenum");
pagenum = coordinatePagenum(!saved || saved < 1 ? 1 : parseInt(saved, 10));
</script>

顯示與隱藏

function showhiddenRecord(pagenum) {
    number.innerHTML = pagenum;

    // 首頁/上一頁:在第一頁時變成純文字
    if (pagenum <= 1) {
        theFirstPage.innerHTML = "第一頁";
        thePrePage.innerHTML   = "上一頁";
    } else {
        theFirstPage.innerHTML = '<a href="javascript:firstPage()">第一頁</a>';
        thePrePage.innerHTML   = '<a href="javascript:prePage()">上一頁</a>';
    }

    // 末頁/下一頁
    if (pagenum >= pageTotal) {
        theNextPage.innerHTML = "下一頁";
        theLastPage.innerHTML = "最後一頁";
    } else {
        theNextPage.innerHTML = '<a href="javascript:nextPage()">下一頁</a>';
        theLastPage.innerHTML = '<a href="javascript:lastPage()">最後一頁</a>';
    }

    document.getElementById('goto').value = pagenum;

    var pageBegin = (record * (pagenum - 1) + 1) | 0;
    var pageEnd   = record * pagenum;

    for (var i = 1; i <= count; i++) {
        mytable.rows[i].style.display = (i >= pageBegin && i <= pageEnd) ? "" : "none";
    }

    Cookie.Set("pagenum", pagenum);
}

function firstPage() { showhiddenRecord(1); }
function lastPage()  { showhiddenRecord(pageTotal); }
function prePage()   { showhiddenRecord(coordinatePagenum(pagenum - 1)); }
function nextPage()  { showhiddenRecord(coordinatePagenum(pagenum + 1)); }
function gotoPage(num) { showhiddenRecord(coordinatePagenum(parseInt(num, 10))); }

頁面結構

<body onload="showhiddenRecord(pagenum)">
<div align="center">
共 6 頁 當前第 <span id="number">1</span> 頁
<span id="theFirstPage"><a href="javascript:firstPage()">第一頁</a></span>
<span id="thePrePage"><a href="javascript:prePage()">上一頁</a></span>
<span id="theNextPage"><a href="javascript:nextPage()">下一頁</a></span>
<span id="theLastPage"><a href="javascript:lastPage()">最後一頁</a></span>
轉到第
<select id="goto" onchange="gotoPage(this.value)">
  <option value="1">1</option><option value="2">2</option>
  <option value="3">3</option><option value="4">4</option>
  <option value="5">5</option><option value="6">6</option>
</select> 頁
</div>

<table id="mytable" cellpadding="4" cellspacing="1" border="0"
       bgcolor="#999999" width="500" align="center">
  <tr bgcolor="#ffffff"><td>標題</td></tr>
  <tr bgcolor="#ffffff"><td>1</td></tr>
  <!-- … 其餘資料列 … -->
</table>
</body>

實務提醒

  • 只適合小資料量:全部列都進 DOM,幾千筆就會明顯卡頓。真實專案請交給後端分頁(LIMIT / OFFSET 或游標分頁)。
  • 可親和性:javascript: 偽協定不利於無障礙與 SEO,改用 <button> 並在 onclick 中 return false 更合適。
  • 避免全域洩漏:範例中 number、theFirstPage 等直接當全域用,是靠 id 變全域的舊瀏覽器行為,請明確用 document.getElementById 或至少在函式內宣告。
  • 用 Cookie 記頁碼:現在請改用 localStorage 或 sessionStorage,API 更乾淨也不受 4KB 與編碼問題限制。
  • 用 class 切換取代逐列 style:幫 body 或 table 加一個 class,用 CSS 的 tbody tr { display:none } 搭配 .on { display:table-row },改動量更小、效能更好。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved