"""Offline Playwright Chromium lab for jQuery EasyUI Ch 22: Get Selected Row Data."""
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 DataGrid Get Selected Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 600px; 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: #f4f4f4; }
tr.dg-row { cursor: pointer; }
tr.dg-row.datagrid-row-selected { background: #ffe48d; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Load Data</div>
<table id="tt">
<thead>
<tr>
<th width="80">Item ID</th>
<th width="80">Product ID</th>
<th width="80" style="text-align:right">List Price</th>
<th width="80" style="text-align:right">Unit Cost</th>
<th width="150">Attribute</th>
<th width="60" style="text-align:center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const DATA = [
{ itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
{ itemid: "EST-10", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted Adult Female", status: "P" },
{ itemid: "EST-11", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
{ itemid: "EST-12", productid: "RP-SN-01", listprice: 26.5, unitcost: 12.0, attr1: "Rattleless", status: "P" },
];
const selectedIndices = [];
const tbody = document.querySelector('#tt tbody');
DATA.forEach((row, idx) => {
const tr = document.createElement('tr');
tr.className = 'dg-row';
tr.dataset.index = String(idx);
tr.innerHTML = `<td>${row.itemid}</td><td>${row.productid}</td><td style="text-align:right">${row.listprice}</td><td style="text-align:right">${row.unitcost}</td><td>${row.attr1}</td><td style="text-align:center">${row.status}</td>`;
tr.addEventListener('click', () => {
const pos = selectedIndices.indexOf(idx);
if (pos >= 0) {
selectedIndices.splice(pos, 1);
tr.classList.remove('datagrid-row-selected');
} else {
selectedIndices.push(idx);
tr.classList.add('datagrid-row-selected');
}
});
tbody.appendChild(tr);
});
window.dgApi = {
getSelected() {
if (selectedIndices.length === 0) return null;
const minIdx = Math.min(...selectedIndices);
return DATA[minIdx];
},
getSelections() {
return [...selectedIndices].sort((a, b) => a - b).map(i => DATA[i]);
},
formatSelectedAlert() {
const row = this.getSelected();
return row ? ('Item ID:' + row.itemid + '\nPrice:' + row.listprice) : null;
},
formatAllIds() {
const ids = [];
const rows = this.getSelections();
for (let i = 0; i < rows.length; i++) ids.push(rows[i].itemid);
return ids.join('\n');
}
};
</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": 700, "height": 420})
page.set_content(HTML_DOC)
# Case 1: No selection returns null / empty array
res1 = page.evaluate("""() => ({
selected: window.dgApi.getSelected(),
selections: window.dgApi.getSelections(),
alertText: window.dgApi.formatSelectedAlert(),
})""")
exp1 = {"selected": None, "selections": [], "alertText": None}
cases.append(dict(name="unselected_returns_null_and_empty", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Single row selection via getSelected
page.click('tr.dg-row[data-index="0"]')
res2 = page.evaluate("""() => ({
itemid: window.dgApi.getSelected().itemid,
listprice: window.dgApi.getSelected().listprice,
alertText: window.dgApi.formatSelectedAlert(),
selectedCount: window.dgApi.getSelections().length,
})""")
exp2 = {
"itemid": "EST-1",
"listprice": 16.5,
"alertText": "Item ID:EST-1\nPrice:16.5",
"selectedCount": 1,
}
cases.append(dict(name="single_row_get_selected", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Multi-row selections via getSelections vs first row via getSelected
page.click('tr.dg-row[data-index="2"]')
page.click('tr.dg-row[data-index="3"]')
res3 = page.evaluate("""() => ({
firstSelectedId: window.dgApi.getSelected().itemid,
selectionIds: window.dgApi.getSelections().map(r => r.itemid),
joinedIds: window.dgApi.formatAllIds(),
})""")
exp3 = {
"firstSelectedId": "EST-1",
"selectionIds": ["EST-1", "EST-11", "EST-12"],
"joinedIds": "EST-1\nEST-11\nEST-12",
}
cases.append(dict(name="multi_row_get_selections_order", 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-datagrid3-lab/explore-datagrid-datagrid3.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid3.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a983.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip