jEasyUI 格式化下拉框
核对 ComboBox 的 valueField、textField 与 formatter(row) 图文项渲染机制及选中/setValue 同步的离线 Chromium 实测。
学完这一章,你能够
- 核对 ComboBox 的 valueField、textField 与 formatter(row) 图文项渲染机制及选中/setValue 同步的离线 Chromium 实测。
使用 formatter 自定义下拉图文项
默认情况下拉框(ComboBox)仅显示纯文本条目;通过配置 `valueField="id"`、`textField="text"` 与 `url="data/combobox_data.json"`,并在 `$('#cc').combobox({ formatter: function(row){ ... } })` 中返回包含 `<img class="item-img" src="images/..."/>` 与 `<span class="item-text">` 的 HTML 片段,即可在下拉面板的每个条目中同时呈现图标与名称。
值域与文本域分离及 setValue 实测观察
本站通过本地回环 JSON 与本地 SVG 图标在 Chromium 中实测 4 条语言选项(`Java`、`C#`、`Ruby`、`Basic`):展开下拉面板后全部 4 项均渲染 `<img class="item-img">` 与 `<span class="item-text">` 且图标实际加载成功(`naturalWidth === 16`);点击 `Ruby(id=3)` 后,`getValue()` 返回 `3`、`getText()` 返回 `"Ruby"`,且输入框显示纯文本 `Ruby` 而非 HTML 源码,下拉面板随之关闭;编程调用 `setValue(1)` 后值、文本与面板选中高亮同步切换为 `Java`。原压缩包未下载。
运行格式化图文 ComboBox 与 valueField/textField 同步实验
"""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()
- 核对 formatter 渲染 4 项图文条目且本地图标加载完成、点击 Ruby 返回 value=3 / text='Ruby' 且输入框保持纯文本,以及 setValue(1) 同步选中态。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:d8245365e201f160a1218eea46c9ad03183b9a6c3966e3f34fbc56838c9193c8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9166279173b189b74813b93ce0ac75bc118a9a47a91ca21bd5399aaeb6b3d168
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 ComboBox 中设置 `formatter` 返回 `<img>` 和 `<span>` HTML 后,选中该条目时输入框里会显示 HTML 标签还是 `textField` 文本?
展开参考解答
`formatter` 仅控制下拉列表面板中每一项的渲染内容;选中后输入框显示的是该记录对应 `textField` 的纯文本值,组件内部值保存的是 `valueField`。