蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 DataGrid 动态切换四列/六列及保留既有属性的离线 Chromium 实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid6.py
explore-datagrid-datagrid6.py186 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 27: Dynamic Columns."""
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 Dynamic Columns Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { border: 1px solid #95b8e7; box-sizing: border-box; }
  .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; }
</style>
</head>
<body>
<div class="dg-panel" id="tt-wrap" style="width:550px;">
  <div class="dg-title" id="tt-title"></div>
  <table id="tt" title="Dynamic Columns" class="easyui-datagrid" style="width:550px;height:250px"
         url="data/datagrid_data.json" singleSelect="true" iconCls="icon-save">
    <thead></thead>
    <tbody></tbody>
  </table>
</div>
<script>
const DATASET = [
  { 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" },
];

const tbl = document.getElementById('tt');
const dgState = {
  options: {
    url: tbl.getAttribute('url'),
    width: 550,
    height: 250,
    singleSelect: tbl.getAttribute('singleSelect') === 'true',
    title: tbl.getAttribute('title'),
    iconCls: tbl.getAttribute('iconCls'),
    columns: [],
  },
  rows: DATASET,
  selectedIdx: null,
};
document.getElementById('tt-title').textContent = dgState.options.title;

window.datagrid = function(newOpts) {
  Object.assign(dgState.options, newOpts);
  dgState.selectedIdx = null;
  const cols = dgState.options.columns[0] || [];
  const thead = tbl.querySelector('thead');
  const tbody = tbl.querySelector('tbody');
  thead.innerHTML = '<tr>' + cols.map(c => `<th data-field="${c.field}" style="width:${c.width}px">${c.title}</th>`).join('') + '</tr>';
  tbody.innerHTML = dgState.rows.map((r, ri) =>
    `<tr data-idx="${ri}">` + cols.map(c => {
      const alignStyle = c.align ? `text-align:${c.align};` : '';
      return `<td data-field="${c.field}" style="${alignStyle}">${r[c.field]}</td>`;
    }).join('') + '</tr>'
  ).join('');
};

window.getGridSnapshot = function() {
  const cols = dgState.options.columns[0] || [];
  const firstRowCells = Array.from(tbl.querySelectorAll('tbody tr:first-child td')).map(td => ({
    field: td.dataset.field,
    text: td.textContent,
    align: td.style.textAlign || 'left',
  }));
  return {
    columnFields: cols.map(c => c.field),
    columnWidths: cols.map(c => c.width),
    preservedOptions: {
      url: dgState.options.url,
      width: dgState.options.width,
      height: dgState.options.height,
      singleSelect: dgState.options.singleSelect,
    },
    rowCount: tbl.querySelectorAll('tbody tr').length,
    firstRowCells,
    selectedIdx: dgState.selectedIdx,
  };
};

// Initial 4-column definition
window.datagrid({
  columns: [[
    { field: 'itemid', title: 'Item ID', width: 80 },
    { field: 'productid', title: 'Product ID', width: 80 },
    { field: 'attr1', title: 'Attribute', width: 200 },
    { field: 'status', title: 'Status', width: 80 },
  ]]
});
</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: Initial 4-column render inheriting declarative options
        res1 = page.evaluate("() => window.getGridSnapshot()")
        exp1 = {
            "columnFields": ["itemid", "productid", "attr1", "status"],
            "columnWidths": [80, 80, 200, 80],
            "preservedOptions": {"url": "data/datagrid_data.json", "width": 550, "height": 250, "singleSelect": True},
            "rowCount": 3,
            "firstRowCells": [
                {"field": "itemid", "text": "EST-1", "align": "left"},
                {"field": "productid", "text": "FI-SW-01", "align": "left"},
                {"field": "attr1", "text": "Large", "align": "left"},
                {"field": "status", "text": "P", "align": "left"},
            ],
            "selectedIdx": None,
        }
        cases.append(dict(name="initial_four_column_render", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Re-invoke datagrid with 6 columns only -> preserves url/width/height/singleSelect
        page.evaluate("""() => window.datagrid({
            columns: [[
                { field: 'itemid', title: 'Item ID', width: 80 },
                { field: 'productid', title: 'Product ID', width: 80 },
                { field: 'listprice', title: 'List Price', width: 80, align: 'right' },
                { field: 'unitcost', title: 'Unit Cost', width: 80, align: 'right' },
                { field: 'attr1', title: 'Attribute', width: 100 },
                { field: 'status', title: 'Status', width: 60 },
            ]]
        })""")
        res2 = page.evaluate("() => window.getGridSnapshot()")
        exp2 = {
            "columnFields": ["itemid", "productid", "listprice", "unitcost", "attr1", "status"],
            "columnWidths": [80, 80, 80, 80, 100, 60],
            "preservedOptions": {"url": "data/datagrid_data.json", "width": 550, "height": 250, "singleSelect": True},
            "rowCount": 3,
            "firstRowCells": [
                {"field": "itemid", "text": "EST-1", "align": "left"},
                {"field": "productid", "text": "FI-SW-01", "align": "left"},
                {"field": "listprice", "text": "16.5", "align": "right"},
                {"field": "unitcost", "text": "10", "align": "right"},
                {"field": "attr1", "text": "Large", "align": "left"},
                {"field": "status", "text": "P", "align": "left"},
            ],
            "selectedIdx": None,
        }
        cases.append(dict(name="dynamic_reinit_six_columns_preserves_options", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Switch back to 4 columns without losing underlying records
        page.evaluate("""() => window.datagrid({
            columns: [[
                { field: 'itemid', title: 'Item ID', width: 80 },
                { field: 'productid', title: 'Product ID', width: 80 },
                { field: 'attr1', title: 'Attribute', width: 200 },
                { field: 'status', title: 'Status', width: 80 },
            ]]
        })""")
        res3 = page.evaluate("""() => ({
            colCount: document.querySelectorAll('#tt thead th').length,
            itemids: Array.from(document.querySelectorAll('#tt tbody td[data-field="itemid"]')).map(td => td.textContent),
            rowCount: document.querySelectorAll('#tt tbody tr').length,
        })""")
        exp3 = {"colCount": 4, "itemids": ["EST-1", "EST-10", "EST-11"], "rowCount": 3}
        cases.append(dict(name="switch_back_and_data_integrity", 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-datagrid6-lab/explore-datagrid-datagrid6.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-datagrid-datagrid6.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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