蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery EasyUI · 本地阅读预览
教程 / 前端开发 / jQuery EasyUI

jEasyUI 添加复选框

核对通过列属性 checkbox="true" 添加勾选列与全选交互,以及配合 idField="itemid" 在分页切换间持久保留跨页选中集合的离线 Chromium 实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

添加复选框列与跨页选择保持机制

为了方便用户在 DataGrid 中批量勾选或取消多行数据,只需在表头新增一列并设置 `checkbox="true"`(如 `<th field="ck" checkbox="true"></th>`),组件会自动生成表头全选框与每行前置复选框。若同时开启分页(`pagination="true"`)并指定唯一主键字段 `idField="itemid"`,则已勾选记录集合将在不同页码之间持久保留,切回原页时对应复选框自动回显勾选状态。本站 Chromium 离线实测验证:单行勾选与表头全选/全不选联动准确;启用 `idField="itemid"` 时在第 1 页勾选 `EST-1`、`EST-3`,翻至第 2 页再勾选 `EST-5` 后,选中集合保持为 `['EST-1', 'EST-3', 'EST-5']`,切回第 1 页时 `EST-1` 与 `EST-3` 复选框仍为勾选态;作为对照,取消 `idField` 后翻页即清空上一页选择(变为空数组 `[]`)。

参考压缩包 `jeasyui-datagrid-datagrid10.zip` 遵循来源站访问停止状态未联网下载并已登记于附件清单;通过本地离线 Chromium 实验可完整核验复选框全选联动及 `idField` 跨页保持差异。

运行 DataGrid 复选框列全选联动与 idField 跨页保持的离线 Chromium 实验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对单选/表头全选与全清、设置 idField="itemid" 跨页累积保留 ['EST-1', 'EST-3', 'EST-5'] 并回显勾选,以及未设 idField 切页清空的对照行为。
运行 DataGrid 复选框列全选联动与 idField 跨页保持的离线 Chromium 实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:98a3534cda8a67f72f7dd0fa8bceebb5b837a953a67dac02767a0821715978b2

下载本站示例源码

本地运行

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

下载jEasyUI 添加复选框实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:dc27879e13e1fca32bb0b8474a894f341ff013d099f73386e7ae83b32c6d6a55

常见错误与边界

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

练习与解答

在分页 DataGrid 中批量勾选多页记录再执行批量导出时,为什么必须配置 `idField` 属性?如果 `idField` 指向的列存在重复值会发生什么?

展开参考解答

DataGrid 依靠 `idField` 唯一标识每条记录从而在换页重建 DOM 后追踪并恢复勾选态;若 `idField` 存在重复值,会导致不同行互相覆盖或误判为同一选中项,引起选中集合错乱。

规范与官方依据