蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

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 单选/多选离线实验

含完整源码 · 151 行
展开查看收起
python
"""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 返回完整数组。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a983.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a983.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`getSelected` 仅返回第一条选中行对象(未选中返回 `null`,需判空防报错);`getSelections` 返回包含全部 3 条记录的数组(未选中返回空数组 `[]`,可直接按 `length` 判断)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习