封裝一個可重複使用的 SplitPage(總筆數, 每頁筆數, 顯示頁碼數) 函數,輸出完整分頁導航 HTML:總筆數/每頁筆數/當前頁/總頁數、首頁/上一頁/頁碼列/下一頁/尾頁、下拉選單跳轉。可直接複製到專案中使用。
<%
' === 通用分頁函數 ===
' 參數: rscount=總筆數, pagesize=每頁筆數, shownum=顯示幾個頁碼連結 (建議 5~10)
Function SplitPage(rscount, pagesize, shownum)
Dim pagenum, curpage, first_page, last_page, up_page, down_page
Dim idx, addr_url, splitpage_html, fbegin, fend
Dim show_front_num, show_back_num
' 當前頁面 URL (去除 QueryString)
addr_url = Request.ServerVariables("URL")
addr_url = Mid(addr_url, InStrRev(addr_url, "/") + 1)
addr_url = addr_url & "?page="
' 計算總頁數
If (rscount Mod pagesize) = 0 Then
pagenum = rscount \ pagesize
Else
pagenum = rscount \ pagesize + 1
End If
If pagenum = 0 Then pagenum = 1 ' 至少 1 頁
first_page = 1
last_page = pagenum
' 取得當前頁碼
curpage = 1
If IsNumeric(Trim(Request.QueryString("page"))) Then
curpage = CInt(Trim(Request.QueryString("page")))
If curpage < 1 Then curpage = 1
If curpage > pagenum Then curpage = pagenum
End If
up_page = curpage - 1
down_page = curpage + 1
' 資訊列
splitpage_html = "共 " & rscount & " 條記錄 " & pagesize & " 條/頁 第 " & curpage & "/" & pagenum & " 頁 "
' 首頁
splitpage_html = splitpage_html & "首頁 "
' 上一頁
If curpage > 1 Then
splitpage_html = splitpage_html & "上一頁 "
Else
splitpage_html = splitpage_html & "上一頁 "
End If
' 計算頁碼顯示範圍 (置中當前頁)
If shownum Mod 2 = 1 Then ' 奇數
show_front_num = shownum \ 2
show_back_num = shownum \ 2
Else ' 偶數
show_front_num = shownum \ 2 - 1
show_back_num = shownum \ 2
End If
If curpage - 1 < show_front_num Then
fbegin = 1
fend = shownum
ElseIf curpage + show_back_num > pagenum Then
fend = pagenum
fbegin = pagenum - shownum + 1
If fbegin < 1 Then fbegin = 1
Else
fbegin = curpage - show_front_num
fend = curpage + show_back_num
End If
' 頁碼列
For idx = fbegin To fend
If idx = curpage Then
splitpage_html = splitpage_html & "" & idx & " "
Else
splitpage_html = splitpage_html & "" & idx & " "
End If
Next
' 下一頁
If pagenum - curpage > 0 Then
splitpage_html = splitpage_html & "下一頁 "
Else
splitpage_html = splitpage_html & "下一頁 "
End If
' 尾頁
splitpage_html = splitpage_html & "尾頁 "
' 下拉跳轉
splitpage_html = splitpage_html & "跳轉到 "
splitpage_html = splitpage_html & ""
Response.Write splitpage_html
End Function
%>
<%
' 在列表頁呼叫
Dim totalRecords, pageSize
totalRecords = 1234 ' 從資料庫 SELECT COUNT(*) 取得
pageSize = 20
Call SplitPage(totalRecords, pageSize, 7) ' 顯示 7 個頁碼
%>
共 1234 條記錄 20 條/頁 第 5/62 頁
首頁
上一頁
2
3
4
5
6
7
8
下一頁
尾頁
跳轉到
?kw=abc&page=2),需解析 Request.ServerVariables("QUERY_STRING") 移除 page 參數後重組 addr_urlclass="pagination"),配合 CSS 美化onclick="loadPage(n);return false;",配合前端局部刷新OFFSET/FETCH、ROW_NUMBER),僅傳入總筆數給此函數這個 SplitPage 函數涵蓋傳統 ASP 分頁 90% 的需求:資訊列、首尾頁、上下頁、置中頁碼列、下拉跳轉。將邏輯封裝為函數,專案中多個列表頁即可複用,維護極為方便。