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

jEasyUI 树形菜单加载父/子节点

核对邻接列表(id/parentId/name)通过 loadFilter 与广度优先 convert(rows) 转换为标准嵌套 Tree 数据结构的实现细节与实测。

学完这一章,你能够

  • 核对邻接列表(id/parentId/name)通过 loadFilter 与广度优先 convert(rows) 转换为标准嵌套 Tree 数据结构的实现细节与实测。

邻接列表数据与 loadFilter 转换入口

数据库表常以邻接列表模型(Adjacency List)保存树结构,即每行仅包含 `id`、`parentId` 与 `name`,而 EasyUI Tree 期望嵌套的 `{id, text, children}` 格式。借助 Tree 提供的 `loadFilter` 回调函数(`loadFilter: function(rows){ return convert(rows); }`),可以在组件渲染前拦截远程 JSON 并就地转换为标准层级结构。

BFS 转换算法、边界行为与离线实测

`convert(rows)` 分两阶段执行:先通过辅助函数 `exists(rows, row.parentId)` 筛选出父节点不存在于当前数组中的顶层节点并压入队列 `toDo`(注意原始示例中首条 `Foods` 记录将字段拼作 `parendId`,由于 `row.parentId` 为 `undefined` 使 `exists` 返回 `false`,仍被识别为根节点,工程落地时应统一拼写为 `parentId`);随后循环出队,查找所有 `row.parentId == node.id` 的子节点挂入 `node.children` 并继续入队,直至整棵树构建完毕。

本站离线 Chromium 实测 10 条邻接列表记录:`loadFilter` 输出 1 个顶层根 `Foods`,二级为 `['Fruits', 'Vegetables']`,三级分别为 `['apple', 'orange']` 与 5 种蔬菜,最终渲染 10 个 DOM `<li>`;进一步验证孤儿 `parentId=999` 或缺失 `parentId` 的记录均安全提升为顶层节点,4 层深链 `L1 -> L2 -> L3 -> L4` 转换深度与路径精确一致。原压缩包未下载。

运行邻接列表 loadFilter 转标准树结构实验

含完整源码 · 228 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 56 (tree-tree6): Adjacency List loadFilter."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright

FLAT_ROWS = [
    {"id": 1, "parendId": 0, "name": "Foods"},
    {"id": 2, "parentId": 1, "name": "Fruits"},
    {"id": 3, "parentId": 1, "name": "Vegetables"},
    {"id": 4, "parentId": 2, "name": "apple"},
    {"id": 5, "parentId": 2, "name": "orange"},
    {"id": 6, "parentId": 3, "name": "tomato"},
    {"id": 7, "parentId": 3, "name": "carrot"},
    {"id": 8, "parentId": 3, "name": "cabbage"},
    {"id": 9, "parentId": 3, "name": "potato"},
    {"id": 10, "parentId": 3, "name": "lettuce"},
]


def start_server():
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            pass

        def do_GET(self):
            if self.path == "/":
                body = HTML_DOC.encode("utf-8")
                ctype = "text/html; charset=utf-8"
            elif self.path == "/data/tree6_data.json":
                body = json.dumps(FLAT_ROWS).encode("utf-8")
                ctype = "application/json; charset=utf-8"
            else:
                self.send_response(404)
                self.end_headers()
                return
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

    srv = HTTPServer(("127.0.0.1", 0), Handler)
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    return srv, srv.server_address[1]


HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery EasyUI Tree loadFilter Offline Lab</title>
</head>
<body>
  <ul id="tt"></ul>
  <script>
    function convert(rows) {
      function exists(list, parentId) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == parentId) return true;
        }
        return false;
      }
      const nodes = [];
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (!exists(rows, row.parentId)) {
          nodes.push({ id: row.id, text: row.name });
        }
      }
      const toDo = [];
      for (let i = 0; i < nodes.length; i++) {
        toDo.push(nodes[i]);
      }
      while (toDo.length) {
        const node = toDo.shift();
        for (let i = 0; i < rows.length; i++) {
          const row = rows[i];
          if (row.parentId == node.id) {
            const child = { id: row.id, text: row.name };
            if (node.children) {
              node.children.push(child);
            } else {
              node.children = [child];
            }
            toDo.push(child);
          }
        }
      }
      return nodes;
    }

    function renderTree(container, nodes) {
      container.innerHTML = '';
      for (const n of nodes) {
        const li = document.createElement('li');
        li.dataset.id = String(n.id);
        const span = document.createElement('span');
        span.textContent = n.text;
        li.appendChild(span);
        if (n.children && n.children.length) {
          const sub = document.createElement('ul');
          renderTree(sub, n.children);
          li.appendChild(sub);
        }
        container.appendChild(li);
      }
    }

    window.__convert = convert;
    window.__converted = null;
    window.__ready = fetch('/data/tree6_data.json')
      .then(r => r.json())
      .then(rows => {
        const treeNodes = convert(rows);
        window.__converted = treeNodes;
        renderTree(document.getElementById('tt'), treeNodes);
      });
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    srv, port = start_server()
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")
            page.evaluate("() => window.__ready")

            # Case 1: Flat adjacency list converted via loadFilter into 3-level nested tree
            res1 = page.evaluate("""() => {
                const root = window.__converted[0];
                return {
                    top_count: window.__converted.length,
                    root_text: root.text,
                    lvl2_texts: root.children.map(c => c.text),
                    fruits_children: root.children[0].children.map(c => c.text),
                    veg_children: root.children[1].children.map(c => c.text),
                    dom_li_count: document.querySelectorAll('#tt li').length
                };
            }""")
            exp1 = {
                "top_count": 1,
                "root_text": "Foods",
                "lvl2_texts": ["Fruits", "Vegetables"],
                "fruits_children": ["apple", "orange"],
                "veg_children": ["tomato", "carrot", "cabbage", "potato", "lettuce"],
                "dom_li_count": 10,
            }
            cases.append({
                "name": "loadfilter_convert_flat_adjacency_to_tree",
                "passed": res1 == exp1,
                "expected": exp1,
                "actual": res1,
            })

            # Case 2: Orphan parentId or missing parentId promoted cleanly to top-level roots
            res2 = page.evaluate("""() => {
                const sample = [
                    { id: 10, parentId: 999, name: 'OrphanRoot' },
                    { id: 11, parentId: 10, name: 'ChildA' },
                    { id: 12, name: 'NoParentKey' }
                ];
                const out = window.__convert(sample);
                return {
                    root_ids: out.map(n => n.id),
                    orphan_children: out[0].children.map(c => c.text),
                    second_has_children: Boolean(out[1].children)
                };
            }""")
            exp2 = {
                "root_ids": [10, 12],
                "orphan_children": ["ChildA"],
                "second_has_children": False,
            }
            cases.append({
                "name": "loadfilter_exists_check_handles_orphan_and_missing_parent",
                "passed": res2 == exp2,
                "expected": exp2,
                "actual": res2,
            })

            # Case 3: 4-level deep hierarchy conversion preserves exact BFS nesting & order
            res3 = page.evaluate("""() => {
                const deep = [
                    { id: 1, parentId: 0, name: 'L1' },
                    { id: 2, parentId: 1, name: 'L2' },
                    { id: 3, parentId: 2, name: 'L3' },
                    { id: 4, parentId: 3, name: 'L4' }
                ];
                const out = window.__convert(deep);
                let cur = out[0], path = [];
                while (cur) {
                    path.push(cur.text);
                    cur = cur.children ? cur.children[0] : null;
                }
                return { depth: path.length, path };
            }""")
            exp3 = {"depth": 4, "path": ["L1", "L2", "L3", "L4"]}
            cases.append({
                "name": "loadfilter_deep_bfs_nesting",
                "passed": res3 == exp3,
                "expected": exp3,
                "actual": res3,
            })

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


if __name__ == "__main__":
    main()
核对 10 条扁平父子记录转换为 3 层嵌套树(Foods 下 2 个分支与 7 个叶子)、孤儿 parentId 提升为根节点,以及 4 层深链 BFS 转换顺序一致。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

即便后端只返回局部子树(子树的顶层记录 `parentId` 非 0)或数据中存在找不到父记录的孤儿节点,`!exists(...)` 也能将其安全识别为当前视图的顶层节点而不会静默丢失。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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