jEasyUI 自定义分页
核对开启 DataGrid pagination="true" 后通过 getPager 获取分页器对象、隐藏页长下拉列表(showPageList:false)、追加自定义按钮与 onBeforeRefresh 拦截控制的离线实测。
学完这一章,你能够
- 核对开启 DataGrid pagination="true" 后通过 getPager 获取分页器对象、隐藏页长下拉列表(showPageList:false)、追加自定义按钮与 onBeforeRefresh 拦截控制的离线实测。
开启内置分页并获取 Pager 对象
DataGrid 内置了完整的底部分页栏,前提是在表格上显式配置 `pagination="true"`,组件才会自动实例化关联的 Pagination(分页器)工具栏。
自定义分页栏按钮与刷新前回调
调用 `var pager = $('#tt').datagrid('getPager')` 拿到分页器对象后,即可再次调用 `pager.pagination({...})` 重新定制外观与交互:设置 `showPageList: false` 隐藏每页条数下拉框,在 `buttons` 数组中追加 `icon-search`、`icon-add`、`icon-edit` 三个带 `handler` 的自定义按钮,并配置 `onBeforeRefresh` 钩子控制是否允许刷新。本站 Chromium 离线实测验证:页长选择器 `<select>` 成功隐藏,3 个自定义按钮准确挂载且点击后依次记录 `['search', 'add', 'edit']`,点击下一页由 `EST-1..EST-3` 切换至 `EST-4..EST-6`;`onBeforeRefresh` 返回 `true` 时刷新计数递增为 `1`,改为返回 `false` 后钩子仍触发但刷新执行被成功拦截(执行计数维持 `1` 不变)。
参考示例包 `jeasyui-datagrid-datagrid11.zip` 遵循来源站访问停止状态未联网下载并已登记于附件清单;运行离线实验脚本即可复现分页栏隐藏列表、自定义按钮与刷新拦截行为。
运行 DataGrid 自定义分页工具栏按钮与 onBeforeRefresh 控制的离线实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 33: Custom Pagination."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Custom Pagination Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 550px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; }
.datagrid-pager { padding: 4px 6px; background: #f4f4f4; border-top: 1px solid #ddd; display: flex; align-items: center; gap: 6px; font-size: 12px; }
.pager-custom-btn { padding: 2px 6px; border: 1px solid #bbb; background: #fff; cursor: pointer; font-size: 11px; }
.hidden { display: none; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Load Data</div>
<table id="tt" pagination="true">
<thead>
<tr>
<th field="itemid" width="80">Item ID</th>
<th field="productid" width="80">Product ID</th>
<th field="listprice" width="80" align="right">List Price</th>
<th field="unitcost" width="80" align="right">Unit Cost</th>
<th field="attr1" width="100">Attribute</th>
<th field="status" width="60" align="center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="pager" class="datagrid-pager">
<select id="page-list"><option value="3">3</option><option value="10">10</option></select>
<button id="btn-prev" type="button">Prev</button>
<span id="page-num">1</span>/<span id="page-total">2</span>
<button id="btn-next" type="button">Next</button>
<button id="btn-refresh" type="button">Refresh</button>
<span id="custom-btns"></span>
</div>
</div>
<script>
const DATA = [
{ itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
{ itemid: "EST-2", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted", status: "P" },
{ itemid: "EST-3", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
{ itemid: "EST-4", productid: "RP-SN-01", listprice: 26.5, unitcost: 12.0, attr1: "Rattleless", status: "P" },
{ itemid: "EST-5", productid: "FL-DSH-01", listprice: 58.5, unitcost: 12.0, attr1: "Tailless", status: "P" },
{ itemid: "EST-6", productid: "AV-CB-01", listprice: 193.5, unitcost: 92.0, attr1: "Adult Male", status: "P" },
];
const state = {
page: 1,
pageSize: 3,
buttonLog: [],
beforeRefreshCalls: 0,
refreshExecutions: 0,
onBeforeRefresh: () => true,
};
function renderPage() {
const start = (state.page - 1) * state.pageSize;
const slice = DATA.slice(start, start + state.pageSize);
const tbody = document.querySelector('#tt tbody');
tbody.innerHTML = slice.map(r =>
`<tr><td>${r.itemid}</td><td>${r.productid}</td><td style="text-align:right">${r.listprice}</td><td style="text-align:right">${r.unitcost}</td><td>${r.attr1}</td><td style="text-align:center">${r.status}</td></tr>`
).join('');
document.getElementById('page-num').textContent = String(state.page);
document.getElementById('page-total').textContent = String(Math.ceil(DATA.length / state.pageSize));
}
const pagerObj = {
pagination(opts) {
const pageList = document.getElementById('page-list');
pageList.classList.toggle('hidden', opts.showPageList === false);
const holder = document.getElementById('custom-btns');
holder.innerHTML = '';
(opts.buttons || []).forEach(btn => {
const el = document.createElement('button');
el.type = 'button';
el.className = 'pager-custom-btn';
el.dataset.iconCls = btn.iconCls;
el.textContent = btn.iconCls;
el.addEventListener('click', btn.handler);
holder.appendChild(el);
});
if (typeof opts.onBeforeRefresh === 'function') {
state.onBeforeRefresh = opts.onBeforeRefresh;
}
}
};
document.getElementById('btn-prev').addEventListener('click', () => {
if (state.page > 1) { state.page -= 1; renderPage(); }
});
document.getElementById('btn-next').addEventListener('click', () => {
if (state.page * state.pageSize < DATA.length) { state.page += 1; renderPage(); }
});
document.getElementById('btn-refresh').addEventListener('click', () => {
const proceed = state.onBeforeRefresh(state.page, state.pageSize);
if (proceed !== false) {
state.refreshExecutions += 1;
renderPage();
}
});
// Initialize DataGrid and customize pager
renderPage();
pagerObj.pagination({
showPageList: false,
buttons: [
{ iconCls: 'icon-search', handler: () => state.buttonLog.push('search') },
{ iconCls: 'icon-add', handler: () => state.buttonLog.push('add') },
{ iconCls: 'icon-edit', handler: () => state.buttonLog.push('edit') },
],
onBeforeRefresh: () => {
state.beforeRefreshCalls += 1;
return true;
}
});
window.pagerApi = {
setBlockRefresh() {
pagerObj.pagination({
showPageList: false,
buttons: [
{ iconCls: 'icon-search', handler: () => state.buttonLog.push('search') },
{ iconCls: 'icon-add', handler: () => state.buttonLog.push('add') },
{ iconCls: 'icon-edit', handler: () => state.buttonLog.push('edit') },
],
onBeforeRefresh: () => {
state.beforeRefreshCalls += 1;
return false;
}
});
},
snapshot() {
return {
pageListVisible: getComputedStyle(document.getElementById('page-list')).display !== 'none',
customIcons: Array.from(document.querySelectorAll('.pager-custom-btn')).map(b => b.dataset.iconCls),
buttonLog: [...state.buttonLog],
page: state.page,
visibleIds: Array.from(document.querySelectorAll('#tt tbody tr td:first-child')).map(td => td.textContent),
beforeRefreshCalls: state.beforeRefreshCalls,
refreshExecutions: state.refreshExecutions,
};
}
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 680, "height": 420})
page.set_content(HTML_DOC)
# Case 1: getPager hides page list & renders 3 custom buttons
snap1 = page.evaluate("() => window.pagerApi.snapshot()")
res1 = {
"pageListVisible": snap1["pageListVisible"],
"customIcons": snap1["customIcons"],
"page1Ids": snap1["visibleIds"],
}
exp1 = {
"pageListVisible": False,
"customIcons": ["icon-search", "icon-add", "icon-edit"],
"page1Ids": ["EST-1", "EST-2", "EST-3"],
}
cases.append(dict(name="get_pager_hide_page_list_and_custom_buttons", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Custom button handlers fire & Next navigates to page 2
page.click('.pager-custom-btn[data-icon-cls="icon-search"]')
page.click('.pager-custom-btn[data-icon-cls="icon-add"]')
page.click('.pager-custom-btn[data-icon-cls="icon-edit"]')
page.click("#btn-next")
snap2 = page.evaluate("() => window.pagerApi.snapshot()")
res2 = {
"buttonLog": snap2["buttonLog"],
"page": snap2["page"],
"page2Ids": snap2["visibleIds"],
}
exp2 = {
"buttonLog": ["search", "add", "edit"],
"page": 2,
"page2Ids": ["EST-4", "EST-5", "EST-6"],
}
cases.append(dict(name="custom_button_handlers_and_page_navigation", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: onBeforeRefresh returning true proceeds, returning false cancels refresh
page.click("#btn-refresh")
after_true = page.evaluate("() => ({ calls: window.pagerApi.snapshot().beforeRefreshCalls, execs: window.pagerApi.snapshot().refreshExecutions })")
page.evaluate("() => window.pagerApi.setBlockRefresh()")
page.click("#btn-refresh")
after_false = page.evaluate("() => ({ calls: window.pagerApi.snapshot().beforeRefreshCalls, execs: window.pagerApi.snapshot().refreshExecutions })")
res3 = {"afterReturnTrue": after_true, "afterReturnFalse": after_false}
exp3 = {
"afterReturnTrue": {"calls": 1, "execs": 1},
"afterReturnFalse": {"calls": 2, "execs": 1},
}
cases.append(dict(name="on_before_refresh_true_vs_false", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
未开启 `pagination` 时网格不会创建底部分页器,后续对 `pager` 配置按钮不会生效;`onBeforeRefresh` 返回 `false` 可在存在未保存编辑内容或前置校验失败时阻止刷新丢失用户修改。