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

jEasyUI 添加工具栏

核对通过 toolbar="#tb" 声明式绑定 DataGrid 顶部工具栏,以及在工具栏内挂载 plain 风格图标按钮并响应点击事件的离线 Chromium 实测。

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

学完这一章,你能够

通过 toolbar 属性声明式绑定工具栏

在数据网格上方集中放置新增、剪切、保存等高频操作按钮,是后台列表页的标准交互。EasyUI 允许直接通过 `toolbar` 属性将外部工具栏容器绑定到 DataGrid 内部。

具体写法无需编写额外初始化 JavaScript:在 `<table id="tt" class="easyui-datagrid" toolbar="#tb">` 上指定选择器 `#tb`,并在页面中定义 `<div id="tb">`,内部放置 3 个 `class="easyui-linkbutton"` 且 `plain="true"` 的按钮(图标类名依次为 `icon-add`、`icon-cut`、`icon-save`)。本站 Chromium 实测解析后 `#tb` 自动挂载到 `.datagrid-wrap` 内部且位于表头正上方(`toolbar.bottom <= thead.top`),3 个按钮均带有 `l-btn-plain` 扁平样式,依次点击后准确触发 `['Add', 'Cut', 'Save']` 回调且不引起页面跳转。

参考压缩包 `jeasyui-datagrid-datagrid4.zip` 未发起外网下载并已登记在附件清单中;通过本站离线 Chromium 脚本可独立复现工具栏挂载位置、按钮图标属性与事件触发顺序。

运行 DataGrid 声明式工具栏挂载与按钮回调的离线 Chromium 实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 24: DataGrid Toolbar."""
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 Toolbar Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .datagrid-wrap { width: 600px; border: 1px solid #95b8e7; box-sizing: border-box; }
  .datagrid-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
  .datagrid-toolbar { background: #f4f4f4; padding: 4px 6px; border-bottom: 1px solid #ddd; display: flex; gap: 6px; }
  .easyui-linkbutton { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; text-decoration: none; color: #333; font-size: 12px; border: 1px solid transparent; }
  .easyui-linkbutton.l-btn-plain:hover { border-color: #95b8e7; background: #eaf2ff; }
  table { width: 100%; border-collapse: collapse; font-size: 12px; }
  th, td { border: 1px solid #ddd; padding: 4px 6px; }
  th { background: #efefef; }
</style>
</head>
<body>
<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
       title="DataGrid with Toolbar" iconCls="icon-save" toolbar="#tb">
  <thead>
    <tr>
      <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="150">Attribute</th>
      <th field="status" width="60" align="center">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>EST-1</td><td>FI-SW-01</td><td style="text-align:right">16.5</td><td style="text-align:right">10.0</td><td>Large</td><td style="text-align:center">P</td></tr>
    <tr><td>EST-10</td><td>K9-DL-01</td><td style="text-align:right">18.5</td><td style="text-align:right">12.0</td><td>Spotted Adult Female</td><td style="text-align:center">P</td></tr>
  </tbody>
</table>
<div id="tb">
  <a href="#" id="btn-add" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="recordAction('Add');return false;">Add</a>
  <a href="#" id="btn-cut" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="recordAction('Cut');return false;">Cut</a>
  <a href="#" id="btn-save" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="recordAction('Save');return false;">Save</a>
</div>
<script>
window.actionLog = [];
window.recordAction = function(name) { window.actionLog.push(name); };

(function parseEasyUI() {
  const tbl = document.getElementById('tt');
  const wrap = document.createElement('div');
  wrap.className = 'datagrid-wrap';
  wrap.id = 'tt-wrap';
  const titleEl = document.createElement('div');
  titleEl.className = 'datagrid-title';
  titleEl.dataset.iconCls = tbl.getAttribute('iconCls');
  titleEl.textContent = tbl.getAttribute('title');
  wrap.appendChild(titleEl);

  const tbSel = tbl.getAttribute('toolbar');
  if (tbSel) {
    const tb = document.querySelector(tbSel);
    tb.classList.add('datagrid-toolbar');
    tb.querySelectorAll('.easyui-linkbutton').forEach(a => {
      if (a.getAttribute('plain') === 'true') a.classList.add('l-btn-plain');
    });
    wrap.appendChild(tb);
  }
  tbl.parentNode.insertBefore(wrap, tbl);
  wrap.appendChild(tbl);
})();
</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": 720, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: Declarative toolbar="#tb" mounts inside DataGrid wrapper above table header
        res1 = page.evaluate("""() => {
            const wrap = document.getElementById('tt-wrap');
            const tb = document.getElementById('tb');
            const thead = document.querySelector('#tt thead');
            const tbRect = tb.getBoundingClientRect();
            const thRect = thead.getBoundingClientRect();
            return {
                toolbarInsideWrap: wrap.contains(tb),
                toolbarAboveHeader: tbRect.bottom <= thRect.top + 1,
                titleText: wrap.querySelector('.datagrid-title').textContent.trim(),
                titleIcon: wrap.querySelector('.datagrid-title').dataset.iconCls,
            };
        }""")
        exp1 = {
            "toolbarInsideWrap": True,
            "toolbarAboveHeader": True,
            "titleText": "DataGrid with Toolbar",
            "titleIcon": "icon-save",
        }
        cases.append(dict(name="declarative_toolbar_binding_position", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Three plain linkbuttons with expected iconCls and labels
        res2 = page.evaluate("""() => Array.from(document.querySelectorAll('#tb .easyui-linkbutton')).map(a => ({
            text: a.textContent.trim(),
            iconCls: a.getAttribute('iconCls'),
            plain: a.classList.contains('l-btn-plain'),
        }))""")
        exp2 = [
            {"text": "Add", "iconCls": "icon-add", "plain": True},
            {"text": "Cut", "iconCls": "icon-cut", "plain": True},
            {"text": "Save", "iconCls": "icon-save", "plain": True},
        ]
        cases.append(dict(name="toolbar_buttons_icons_and_plain", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Clicking toolbar buttons fires action handlers in order without navigation
        url_before = page.url
        page.click("#btn-add")
        page.click("#btn-cut")
        page.click("#btn-save")
        res3 = {
            "actions": page.evaluate("() => window.actionLog"),
            "urlUnchanged": (page.url == url_before),
        }
        exp3 = {"actions": ["Add", "Cut", "Save"], "urlUnchanged": True}
        cases.append(dict(name="toolbar_click_handlers_fire", expected=exp3, actual=res3, passed=(res3 == exp3)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 toolbar="#tb" 挂载于表头上方、3 个 plain 链接按钮图标类名(icon-add/icon-cut/icon-save)以及依次点击触发 ['Add', 'Cut', 'Save']。
运行 DataGrid 声明式工具栏挂载与按钮回调的离线 Chromium 实验

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

当前源码 SHA256:4c5d811fb41753a90bbe0e4300163a63f85e1d4d0d276ecdb9de9dd11cc12ae6

下载本站示例源码

本地运行

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

下载jEasyUI 添加工具栏实验

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

ZIP SHA256:d16c88f6b7f14f1fb3e3c96a2cbac9449f197a9c8822ec30f53502007be523a5

常见错误与边界

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

练习与解答

通过 `toolbar="#tb"` 引用 DOM 元素与在 JS 中传入 `toolbar: [{text, iconCls, handler}]` 数组两种方式,各自适合什么场景?

展开参考解答

数组方式适合纯按钮的简单工具栏,代码简洁;引用 `#tb` DOM 容器方式则适合需要自定义布局、嵌套输入框或混合多种表单控件的工具栏。

规范与官方依据