"""Offline Playwright Chromium lab for jQuery EasyUI Ch 32: Checkbox Column."""
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 Checkbox Select Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 560px; 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; }
tr.selected { background: #ffe48d; }
.dg-pager { padding: 5px 8px; background: #f4f4f4; border-top: 1px solid #ddd; display: flex; gap: 8px; font-size: 12px; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Checkbox Select</div>
<table id="tt" idField="itemid" pagination="true">
<thead>
<tr>
<th field="ck" checkbox="true" style="width:28px;text-align:center"><input type="checkbox" id="chk-all"></th>
<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 class="dg-pager">
<button id="btn-p1" type="button">Page 1</button>
<button id="btn-p2" type="button">Page 2</button>
<span id="page-label"></span>
</div>
</div>
<script>
const ALL_ROWS = [
{ 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, idField: 'itemid', selectedMap: new Map() };
const chkAll = document.getElementById('chk-all');
function currentPageRows() {
const start = (state.page - 1) * state.pageSize;
return ALL_ROWS.slice(start, start + state.pageSize);
}
function syncHeaderCheckbox() {
const pageRows = currentPageRows();
chkAll.checked = pageRows.length > 0 && pageRows.every(r => state.selectedMap.has(r.itemid));
}
function renderPage(pageNum) {
if (!state.idField && pageNum !== state.page) {
state.selectedMap.clear();
}
state.page = pageNum;
const tbody = document.querySelector('#tt tbody');
tbody.innerHTML = '';
currentPageRows().forEach(r => {
const isSel = state.selectedMap.has(r.itemid);
const tr = document.createElement('tr');
tr.dataset.itemid = r.itemid;
if (isSel) tr.classList.add('selected');
tr.innerHTML = `<td style="text-align:center"><input type="checkbox" class="row-chk" data-itemid="${r.itemid}" ${isSel ? 'checked' : ''}></td><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>`;
const cb = tr.querySelector('.row-chk');
cb.addEventListener('change', () => {
if (cb.checked) {
state.selectedMap.set(r.itemid, r);
tr.classList.add('selected');
} else {
state.selectedMap.delete(r.itemid);
tr.classList.remove('selected');
}
syncHeaderCheckbox();
});
tbody.appendChild(tr);
});
syncHeaderCheckbox();
document.getElementById('page-label').textContent = `Page ${state.page}`;
}
chkAll.addEventListener('change', () => {
currentPageRows().forEach(r => {
if (chkAll.checked) state.selectedMap.set(r.itemid, r);
else state.selectedMap.delete(r.itemid);
});
renderPage(state.page);
});
document.getElementById('btn-p1').addEventListener('click', () => renderPage(1));
document.getElementById('btn-p2').addEventListener('click', () => renderPage(2));
window.chkGridApi = {
setIdField(field) { state.idField = field; state.selectedMap.clear(); renderPage(1); },
getSelections() { return Array.from(state.selectedMap.keys()); },
checkedOnPage() { return Array.from(document.querySelectorAll('.row-chk:checked')).map(el => el.dataset.itemid); },
headerChecked() { return chkAll.checked; },
};
renderPage(1);
</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: Single checkbox toggle + header select-all / deselect-all
page.click('input.row-chk[data-itemid="EST-1"]')
after_one = page.evaluate("() => ({ sel: window.chkGridApi.getSelections(), hdr: window.chkGridApi.headerChecked() })")
page.click("#chk-all")
after_all = page.evaluate("() => ({ sel: window.chkGridApi.getSelections(), hdr: window.chkGridApi.headerChecked() })")
page.click("#chk-all")
after_clear = page.evaluate("() => ({ sel: window.chkGridApi.getSelections(), hdr: window.chkGridApi.headerChecked() })")
res1 = {"afterOne": after_one, "afterAll": after_all, "afterClear": after_clear}
exp1 = {
"afterOne": {"sel": ["EST-1"], "hdr": False},
"afterAll": {"sel": ["EST-1", "EST-2", "EST-3"], "hdr": True},
"afterClear": {"sel": [], "hdr": False},
}
cases.append(dict(name="checkbox_column_single_toggle_and_select_all", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: idField="itemid" preserves selections across pages
page.click('input.row-chk[data-itemid="EST-1"]')
page.click('input.row-chk[data-itemid="EST-3"]')
page.click("#btn-p2")
page.click('input.row-chk[data-itemid="EST-5"]')
sel_on_p2 = page.evaluate("() => window.chkGridApi.getSelections()")
page.click("#btn-p1")
res2 = page.evaluate("""(selP2) => ({
selectionsOnPage2: selP2,
selectionsBackOnPage1: window.chkGridApi.getSelections(),
checkedBoxesOnPage1: window.chkGridApi.checkedOnPage(),
})""", sel_on_p2)
exp2 = {
"selectionsOnPage2": ["EST-1", "EST-3", "EST-5"],
"selectionsBackOnPage1": ["EST-1", "EST-3", "EST-5"],
"checkedBoxesOnPage1": ["EST-1", "EST-3"],
}
cases.append(dict(name="idfield_persists_selection_across_pages", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Without idField, switching pages clears cross-page selections
page.evaluate("() => window.chkGridApi.setIdField(null)")
page.click('input.row-chk[data-itemid="EST-2"]')
before_switch = page.evaluate("() => window.chkGridApi.getSelections()")
page.click("#btn-p2")
after_switch = page.evaluate("() => window.chkGridApi.getSelections()")
res3 = {"beforePageSwitch": before_switch, "afterPageSwitch": after_switch}
exp3 = {"beforePageSwitch": ["EST-2"], "afterPageSwitch": []}
cases.append(dict(name="without_idfield_clears_cross_page_selection", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jeasyui-datagrid-datagrid10-lab/explore-datagrid-datagrid10.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid10.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a966.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip