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

jQuery EasyUI 简介

理解 jQuery EasyUI 核心特性、官方版本获取渠道,以及基于 HTML5 data-options 声明与 JavaScript 代码编程两种创建 UI 组件的方式。

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

学完这一章,你能够

什么是 jQuery EasyUI 与核心特点

jQuery EasyUI 是基于 jQuery 核心打造的界面组件框架,集成了丰富的 UI 插件,为构建传统富客户端风格的网页应用提供一整套现成基础设施。

其主要优势体现在六个方面:依托 jQuery 生态集成多种 UI 插件;提供构建现代化交互式 JavaScript 应用所需的基础组件;支持以少量 HTML 标记声明界面而显著减少手写脚本量;形成覆盖完整网页布局与控件的框架体系;有效压缩产品研发周期与维护规模;同时兼顾上手简洁与功能完备。

版本获取与两种组件声明方式

开发者可前往官方下载页 `http://www.jeasyui.com/download/index.php` 按需获取对应的 jQuery EasyUI 发布包(包含脚本、主题样式与图标资源)。

借助 jQuery 核心与 HTML5 自定义属性机制,jQuery EasyUI 支持两种声明和初始化 UI 组件的路径。第一种是直接在 HTML 中声明:为元素添加 `easyui-<插件名>` 类名,并通过 `data-options` 传入配置项(如 `<div class="easyui-dialog" style="width:400px;height:200px" data-options="title:'My Dialog',collapsible:true,iconCls:'icon-ok',onOpen:function(){}">`)。本站离线 Chromium 实测该声明式对话框渲染尺寸为 `400×200`,标题为 `My Dialog`,带有 `icon-ok` 图标类与正文 `dialog content.`,初始化时触发 `onOpen` 计数为 `1`,点击折叠按钮后主体立即隐藏。

第二种是先在 HTML 中放置基础占位元素(如 `<input id="cc" style="width:200px" />`),再通过 JavaScript 调用插件方法 `$('#cc').combobox({url: ..., required: true, valueField: 'id', textField: 'text'})` 编程式实例化。本站通过本地回环 `/combo_data.json`(3 条选项)在 Chromium 中实测:未选择时必填校验 `isValid` 返回 `false`,展开下拉并选择 `id='2'`(`JavaScript API`)后 `isValid` 转为 `true`,`getValue()`/`getText()` 分别返回 `'2'` 与 `'JavaScript API'`;同时对比声明式与编程式对话框,二者在标题、图标类及可折叠状态上完全一致(`totalOpenCalls = 2`)。

离线 Chromium 验证 HTML data-options 声明式对话框与 JS 编程式 ComboBox

python · 阅读源码
"""Offline Playwright Chromium verification lab for jQuery EasyUI Intro (Ch02)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright

COMBO_ITEMS = [
    {"id": "1", "text": "HTML5 Markup"},
    {"id": "2", "text": "JavaScript API"},
    {"id": "3", "text": "DataGrid Plugin"},
]


class ComboHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

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


HTML_DOC = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Intro Lab</title>
<style>
  body { font-family: Arial, sans-serif; margin: 16px; }
  .window { border: 1px solid #95b8e7; box-sizing: border-box; background: #fff; }
  .panel-header { background: #e0ecff; padding: 6px 8px; display: flex; justify-content: space-between; align-items: center; }
  .panel-title { font-weight: bold; }
  .panel-body { padding: 10px; }
  .hidden { display: none; }
  .combo-wrap { position: relative; display: inline-block; margin-top: 16px; }
  .combo-panel { border: 1px solid #95b8e7; background: #fff; position: absolute; left: 0; top: 100%; width: 100%; box-sizing: border-box; }
  .combobox-item { padding: 4px 8px; cursor: pointer; }
  .combobox-item.selected { background: #ffe48d; }
  .validatebox-invalid { border: 1px solid #d9534f; background: #fff3f3; }
</style>
</head>
<body>
  <div id="dlg1" class="easyui-dialog" style="width:400px;height:200px"
       data-options="title:'My Dialog',collapsible:true,iconCls:'icon-ok',onOpen:function(){ window.__openCount += 1; }">
      dialog content.
  </div>

  <div style="margin-top:20px;">
    <input id="cc" style="width:200px" />
  </div>

  <div id="dlg2" style="width:400px;height:200px">programmatic dialog content.</div>

  <script>
    window.__openCount = 0;

    function parseDataOptions(el) {
      const raw = (el.getAttribute('data-options') || '').trim();
      if (!raw) return {};
      return Function('"use strict"; return ({' + raw + '});')();
    }

    function initDialog(el, opts) {
      const cfg = Object.assign({ title: '', collapsible: false, iconCls: '', onOpen: null }, opts || {});
      const content = el.innerHTML.trim();
      el.innerHTML = '';
      el.classList.add('window');
      const header = document.createElement('div');
      header.className = 'panel-header';
      const titleSpan = document.createElement('span');
      titleSpan.className = 'panel-title ' + cfg.iconCls;
      titleSpan.textContent = cfg.title;
      header.appendChild(titleSpan);
      let collapseBtn = null;
      if (cfg.collapsible) {
        collapseBtn = document.createElement('button');
        collapseBtn.type = 'button';
        collapseBtn.className = 'panel-tool-collapse';
        collapseBtn.textContent = '−';
        header.appendChild(collapseBtn);
      }
      const body = document.createElement('div');
      body.className = 'panel-body';
      body.textContent = content;
      el.appendChild(header);
      el.appendChild(body);
      el.__dialogState = { title: cfg.title, iconCls: cfg.iconCls, collapsible: cfg.collapsible, collapsed: false };
      if (collapseBtn) {
        collapseBtn.addEventListener('click', () => {
          el.__dialogState.collapsed = !el.__dialogState.collapsed;
          body.classList.toggle('hidden', el.__dialogState.collapsed);
        });
      }
      if (typeof cfg.onOpen === 'function') cfg.onOpen.call(el);
      return el.__dialogState;
    }

    // Minimal jQuery-like wrapper supporting .dialog() and .combobox()
    function $(sel) {
      const el = typeof sel === 'string' ? document.querySelector(sel) : sel;
      return {
        dialog(arg) {
          if (typeof arg === 'string' && arg === 'options') return el.__dialogState;
          initDialog(el, arg);
          return this;
        },
        combobox(arg) {
          if (arg === 'getValue') return el.__combo.value;
          if (arg === 'getText') return el.__combo.text;
          if (arg === 'isValid') {
            const valid = !el.__combo.required || Boolean(el.__combo.value);
            el.classList.toggle('validatebox-invalid', !valid);
            return valid;
          }
          const cfg = Object.assign({ url: '', required: false, valueField: 'id', textField: 'text' }, arg || {});
          const wrap = document.createElement('div');
          wrap.className = 'combo-wrap';
          el.parentNode.insertBefore(wrap, el);
          wrap.appendChild(el);
          const arrow = document.createElement('button');
          arrow.type = 'button';
          arrow.id = el.id + '-arrow';
          arrow.textContent = '▼';
          wrap.appendChild(arrow);
          const panel = document.createElement('div');
          panel.id = el.id + '-panel';
          panel.className = 'combo-panel hidden';
          wrap.appendChild(panel);
          el.__combo = { value: '', text: '', required: cfg.required, items: [], loaded: false };
          arrow.addEventListener('click', () => panel.classList.toggle('hidden'));
          el.__comboReady = fetch(cfg.url).then(r => r.json()).then(rows => {
            el.__combo.items = rows;
            el.__combo.loaded = true;
            panel.innerHTML = '';
            rows.forEach(item => {
              const div = document.createElement('div');
              div.className = 'combobox-item';
              div.dataset.value = item[cfg.valueField];
              div.textContent = item[cfg.textField];
              div.addEventListener('click', () => {
                el.__combo.value = String(item[cfg.valueField]);
                el.__combo.text = String(item[cfg.textField]);
                el.value = el.__combo.text;
                panel.querySelectorAll('.combobox-item').forEach(x => x.classList.remove('selected'));
                div.classList.add('selected');
                panel.classList.add('hidden');
                el.classList.remove('validatebox-invalid');
              });
              panel.appendChild(div);
            });
          });
          return this;
        }
      };
    }
    window.$ = $;

    // 1. Declarative parser
    document.querySelectorAll('.easyui-dialog').forEach(el => {
      initDialog(el, parseDataOptions(el));
    });

    // 2. Programmatic combobox
    $('#cc').combobox({
      url: '/combo_data.json',
      required: true,
      valueField: 'id',
      textField: 'text'
    });
  </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():
    server = ThreadingHTTPServer(("127.0.0.1", 0), ComboHandler)
    port = server.server_address[1]
    t = threading.Thread(target=server.serve_forever, daemon=True)
    t.start()
    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("() => document.getElementById('cc').__comboReady")

            # Case 1: Declarative HTML dialog parsing & collapse interaction
            before = page.evaluate("""() => {
                const el = document.getElementById('dlg1');
                const rect = el.getBoundingClientRect();
                return {
                    title: el.querySelector('.panel-title').textContent,
                    hasIconOk: el.querySelector('.panel-title').classList.contains('icon-ok'),
                    body: el.querySelector('.panel-body').textContent,
                    width: Math.round(rect.width),
                    height: Math.round(rect.height),
                    openCount: window.__openCount
                };
            }""")
            page.click("#dlg1 .panel-tool-collapse")
            collapsed = page.evaluate("() => document.querySelector('#dlg1 .panel-body').classList.contains('hidden')")
            act1 = dict(before, collapsedAfterClick=collapsed)
            exp1 = {
                "title": "My Dialog",
                "hasIconOk": True,
                "body": "dialog content.",
                "width": 400,
                "height": 200,
                "openCount": 1,
                "collapsedAfterClick": True,
            }
            cases.append({
                "name": "html_declarative_dialog",
                "expected": exp1,
                "actual": act1,
                "passed": act1 == exp1,
            })

            # Case 2: Programmatic JS combobox with required validation & selection
            valid_empty = page.evaluate("() => $('#cc').combobox('isValid')")
            page.click("#cc-arrow")
            page.click('#cc-panel .combobox-item[data-value="2"]')
            act2 = page.evaluate("""(validEmpty) => ({
                validWhenEmpty: validEmpty,
                validAfterSelect: $('#cc').combobox('isValid'),
                value: $('#cc').combobox('getValue'),
                text: $('#cc').combobox('getText'),
                itemCount: document.querySelectorAll('#cc-panel .combobox-item').length
            })""", valid_empty)
            exp2 = {
                "validWhenEmpty": False,
                "validAfterSelect": True,
                "value": "2",
                "text": "JavaScript API",
                "itemCount": 3,
            }
            cases.append({
                "name": "js_programmatic_combobox",
                "expected": exp2,
                "actual": act2,
                "passed": act2 == exp2,
            })

            # Case 3: Declarative vs Programmatic dialog API parity
            act3 = page.evaluate("""() => {
                $('#dlg2').dialog({
                    title: 'My Dialog',
                    collapsible: true,
                    iconCls: 'icon-ok',
                    onOpen: function() { window.__openCount += 1; }
                });
                const d1 = $('#dlg1').dialog('options');
                const d2 = $('#dlg2').dialog('options');
                return {
                    sameTitle: d1.title === d2.title,
                    sameIcon: d1.iconCls === d2.iconCls,
                    sameCollapsible: d1.collapsible === d2.collapsible,
                    totalOpenCalls: window.__openCount
                };
            }""")
            exp3 = {
                "sameTitle": True,
                "sameIcon": True,
                "sameCollapsible": True,
                "totalOpenCalls": 2,
            }
            cases.append({
                "name": "declarative_vs_programmatic_parity",
                "expected": exp3,
                "actual": act3,
                "passed": act3 == exp3,
            })

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 400×200 声明式 Dialog 的标题、图标类、onOpen 回调与折叠交互,ComboBox 本地 JSON 异步加载与必填校验,以及两种创建方式的选项一致性。
离线 Chromium 验证 HTML data-options 声明式对话框与 JS 编程式 ComboBox

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

当前源码 SHA256:f059dbea82b775ab7898ac63e50c07703cdb33c65c6a643b3c2c823668ce8f82

下载本站示例源码

本地运行

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

下载jQuery EasyUI 简介实验

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

ZIP SHA256:6cdaf722bede746657a8bb6528f1ef236fa5fbcf1f2421a90bca42794f1e8867

常见错误与边界

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

练习与解答

在 jQuery EasyUI 中,HTML 声明式初始化与 JavaScript 编程式初始化分别适合什么场景?

展开参考解答

静态结构固定的页面控件可直接用 class='easyui-*' 加 data-options 声明以减少模板代码;需要根据运行时状态、异步接口地址或复杂回调函数动态配置的组件更适合用 JavaScript 编程式创建。

规范与官方依据