jEasyUI 取得选中行数据
核对 DataGrid 检索选中记录的 getSelected(返回首条记录或 null)与 getSelections(返回全部选中记录数组)两种方法的语义差异与离线交互实测。
学完这一章,你能够
- 核对 DataGrid 检索选中记录的 getSelected(返回首条记录或 null)与 getSelections(返回全部选中记录数组)两种方法的语义差异与离线交互实测。
检索选中行的两种核心方法
在 DataGrid 中读取用户当前选中的数据行时,组件提供两个常用 API:`getSelected` 返回第一个被选中的行记录对象,未选中任何行时返回 `null`;`getSelections` 返回包含全部选中行对象的数组,未选中时返回空数组 `[]`。
表格声明与单选/多选读取实测
首先创建宽 `600px`、高 `250px` 的 DataGrid(`id="tt"`),配置 `url="data/datagrid_data.json"`、`title="Load Data"` 与 `iconCls="icon-save"`,并声明 `itemid`、`productid`、`listprice`、`unitcost`、`attr1`、`status` 六列(价格列右对齐、状态列居中)。
调用 `$('#tt').datagrid('getSelected')` 时务必先判断返回值非空再读取 `row.itemid` 与 `row.listprice`;需要批量处理多行时,则调用 `getSelections` 遍历数组收集所有 `rows[i].itemid` 并拼接展示。本站 Chromium 离线实测验证:未选中时 `getSelected()` 为 `null`、`getSelections()` 为 `[]`;点击首行后 `getSelected()` 精准返回 `EST-1`(价格 `16.5`)并拼出 `'Item ID:EST-1\nPrice:16.5'`;继续选中第 3、4 行后,`getSelected()` 仍返回首条选中记录 `EST-1`,而 `getSelections()` 返回全部 3 条记录(`['EST-1', 'EST-11', 'EST-12']`)。
示例压缩包 `jeasyui-datagrid-datagrid3.zip` 未发起外网下载并已登记于附件清单;通过本地离线实验脚本可直接复现空选、单选与多选读取结果。
运行 DataGrid getSelected 与 getSelections 单选/多选离线实验
"""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()
- 核对空选返回 null/[]、单选输出 Item ID:EST-1 与 Price:16.5,以及多选三行时 getSelected 返回首条、getSelections 返回完整数组。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:5e9f11ddcc2fb3b10c64b788a067c58ebd6eb8c04b0bf9f4a44b03a48cecd3e4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0a41bc88c15a11cb0b11cf4e7f228eb07b12e42d81544ae46c5527e3b41262ec
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在多选模式下同时选中 3 行时,`getSelected` 与 `getSelections` 的返回值分别是什么?未选中任何行时两者如何区分处理?
展开参考解答
`getSelected` 仅返回第一条选中行对象(未选中返回 `null`,需判空防报错);`getSelections` 返回包含全部 3 条记录的数组(未选中返回空数组 `[]`,可直接按 `length` 判断)。