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

运行格式化图文 ComboBox 与 valueField/textField 同步实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-form-form4.py
explore-form-form4.py215 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 65 (form-form4): Formatted ComboBox."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright

COMBO_DATA = [
    {"id": 1, "text": "Java", "icon": "java.svg"},
    {"id": 2, "text": "C#", "icon": "csharp.svg"},
    {"id": 3, "text": "Ruby", "icon": "ruby.svg"},
    {"id": 4, "text": "Basic", "icon": "basic.svg"},
]

SVG_ICON = (
    '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">'
    '<rect width="16" height="16" rx="3" fill="#2563eb"/>'
    '<circle cx="8" cy="8" r="4" fill="#ffffff"/></svg>'
)


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/combobox_data.json":
                body = json.dumps(COMBO_DATA).encode("utf-8")
                ctype = "application/json; charset=utf-8"
            elif self.path.startswith("/images/") and self.path.endswith(".svg"):
                body = SVG_ICON.encode("utf-8")
                ctype = "image/svg+xml"
            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 Formatted ComboBox Offline Lab</title>
  <style>
    .combo-panel { display: none; border: 1px solid #94a3b8; width: 140px; background: #fff; }
    .combo-panel.open { display: block; }
    .combobox-item { display: flex; align-items: center; gap: 6px; padding: 4px 6px; cursor: pointer; }
    .combobox-item-selected { background: #ffe48d; }
    .item-img { width: 16px; height: 16px; }
  </style>
</head>
<body>
  <input id="cc" style="width:100px" url="/data/combobox_data.json" valueField="id" textField="text">
  <button id="toggle-btn" type="button">▼</button>
  <div id="cc-panel" class="combo-panel"></div>
  <script>
    (function () {
      const inp = document.getElementById('cc');
      const panel = document.getElementById('cc-panel');
      const valueField = inp.getAttribute('valueField');
      const textField = inp.getAttribute('textField');
      let rows = [];
      let currentVal = '';
      let currentText = '';

      document.getElementById('toggle-btn').addEventListener('click', () => panel.classList.toggle('open'));

      function selectById(val) {
        const hit = rows.find(r => String(r[valueField]) === String(val));
        if (!hit) return;
        currentVal = hit[valueField];
        currentText = hit[textField];
        inp.value = currentText;
        panel.querySelectorAll('.combobox-item').forEach(el => {
          el.classList.toggle('combobox-item-selected', el.dataset.val === String(currentVal));
        });
        panel.classList.remove('open');
      }

      window.$ = (sel) => ({
        combobox: (arg1, arg2) => {
          if (typeof arg1 === 'object') {
            const formatter = arg1.formatter;
            return fetch(inp.getAttribute('url')).then(r => r.json()).then(data => {
              rows = data;
              panel.innerHTML = '';
              for (const row of rows) {
                const item = document.createElement('div');
                item.className = 'combobox-item';
                item.dataset.val = String(row[valueField]);
                item.innerHTML = formatter ? formatter(row) : String(row[textField]);
                item.addEventListener('click', () => selectById(row[valueField]));
                panel.appendChild(item);
              }
            });
          }
          if (arg1 === 'getValue') return currentVal;
          if (arg1 === 'getText') return currentText;
          if (arg1 === 'setValue') { selectById(arg2); return; }
        }
      });

      window.__ready = $('#cc').combobox({
        formatter: function (row) {
          const imageFile = '/images/' + row.icon;
          return '<img class="item-img" src="' + imageFile + '"/><span class="item-text">' + row.text + '</span>';
        }
      });
    })();
  </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: Formatter renders <img> and <span> in every dropdown item with real loaded SVG icons
            page.click('#toggle-btn')
            page.wait_for_function("() => Array.from(document.querySelectorAll('.item-img')).every(img => img.complete && img.naturalWidth > 0)")
            res1 = page.evaluate("""() => {
                const items = Array.from(document.querySelectorAll('.combobox-item'));
                return {
                    item_count: items.length,
                    img_srcs: items.map(el => new URL(el.querySelector('img.item-img').src).pathname),
                    texts: items.map(el => el.querySelector('span.item-text').textContent),
                    all_imgs_loaded: items.every(el => {
                        const img = el.querySelector('img.item-img');
                        return img.complete && img.naturalWidth === 16;
                    })
                };
            }""")
            exp1 = {
                "item_count": 4,
                "img_srcs": ["/images/java.svg", "/images/csharp.svg", "/images/ruby.svg", "/images/basic.svg"],
                "texts": ["Java", "C#", "Ruby", "Basic"],
                "all_imgs_loaded": True,
            }
            cases.append({
                "name": "combobox_formatter_renders_icon_and_text_items",
                "passed": res1 == exp1,
                "expected": exp1,
                "actual": res1,
            })

            # Case 2: Clicking Ruby sets valueField (3) & textField ('Ruby'), keeping input plain text
            page.click('.combobox-item[data-val="3"]')
            res2 = page.evaluate("""() => ({
                value: $('#cc').combobox('getValue'),
                text: $('#cc').combobox('getText'),
                input_value: document.getElementById('cc').value,
                panel_open: document.getElementById('cc-panel').classList.contains('open')
            })""")
            exp2 = {"value": 3, "text": "Ruby", "input_value": "Ruby", "panel_open": False}
            cases.append({
                "name": "combobox_select_separates_valuefield_and_textfield",
                "passed": res2 == exp2,
                "expected": exp2,
                "actual": res2,
            })

            # Case 3: Programmatic setValue(1) updates text, input value, and selected item class
            res3 = page.evaluate("""() => {
                $('#cc').combobox('setValue', 1);
                return {
                    value: $('#cc').combobox('getValue'),
                    text: $('#cc').combobox('getText'),
                    selected_val: document.querySelector('.combobox-item-selected').dataset.val
                };
            }""")
            exp3 = {"value": 1, "text": "Java", "selected_val": "1"}
            cases.append({
                "name": "combobox_setvalue_syncs_selection_state",
                "passed": res3 == exp3,
                "expected": exp3,
                "actual": res3,
            })

            browser.close()
    finally:
        srv.shutdown()
    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-form-form4-lab/explore-form-form4.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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