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

自动完成(Autocomplete)

核对 jQuery UI Autocomplete 的本地数组过滤、重音折叠、分类分组、组合框、自定义项渲染、多值输入、远程 JSON/JSONP/缓存、滚动菜单与 XML 数据解析。

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

学完这一章,你能够

默认数组数据源与重音字符匹配

Autocomplete 部件根据用户输入实时过滤候选清单,帮助快速定位并选取预设值。最简用法是通过 `source` 传入 JavaScript 字符串数组(如 22 种编程语言列表);在输入框键入 `'ja'` 时即匹配出 `['Java', 'JavaScript']`(完整选项与事件见官方 Autocomplete Widget API)。

面对带变音符的人名或词条,可自定义 `source(request, response)` 回调:对候选项执行重音归一化(如 `á -> a`、`ö -> o`),使无重音输入能同时匹配原值与归一化值,而输入重音字符时仅保留精确含重音的词条。本站离线 Chromium 实测:键入 `'Jo'` 返回 `['Jörn Zaefferer', 'John Resig']`,键入 `'Jö'` 仅返回 `['Jörn Zaefferer']`。

分类建议、自定义渲染与组合框/滚动菜单

通过 `$.widget('custom.catcomplete', $.ui.autocomplete, ...)` 覆写 `_renderMenu`,可在类别切换时插入 `.ui-autocomplete-category` 分组标题;若数据项含自定义字段(如 `label`、`value`、`desc`、`icon`),可覆写 `_renderItem` 与 `focus`/`select` 回调并 `return false` 接管回填行为。本站实测分类查询 `'a'` 产出 `9` 条建议与 `['Products', 'People']` 两个分组头;自定义项目查询 `'j'` 匹配 `3` 项,选中第二项后同步回填标签 `'jQuery UI'`、隐藏 ID `'jquery-ui'`、描述文本与图标路径 `'images/jqueryui_32x32.png'`。

组合框(Combobox)演示了如何组合 Autocomplete、Button 与 Tooltip 包装原生 `<select>`:既能按输入过滤,也可点击下拉按钮以空串触发完整列表,失焦时校验无效文本并清空提示(该示例属定制演示部件而非官方独立正式控件)。对于较长候选列表,只需给 `.ui-autocomplete` 设置 `max-height` 与 `overflow-y: auto; overflow-x: hidden` 即可纵向滚动。本站实测组合框从 `4` 个有效选项中选定 `'Python'` 后同步更新 `<select>`,输入无效值 `'NoSuchLang'` 后自动清空并设置错误提示;长列表在 `100px` 限高下确认产生纵向溢出滚动(`scrollHeight > clientHeight`)。

单一输入框多值自动完成(本地与远程)

要在单个输入框连续选取多个值,可用 `split(/,\s*/)` 与 `extractLast()` 提取最后一个逗号后的当前片段参与过滤,在 `focus` 返回 `false` 防止高亮预览覆盖已有值,在 `select` 中替换末尾片段并追加 `', '` 分隔符,同时拦截激活菜单时的 `Tab` 键防止失焦。远程多值模式将过滤改为向后端接口发送 `term` 参数,并在 `search` 回调中拦截末尾片段长度小于 `2` 的请求。本站实测本地依次选取后得到 `'Java, Python, '`;远程模式 1 字符 `'e'` 被拦截,依次查询 `'ea'` 与 `'go'` 后拼接为 `'Bald Eagle, Golden Eagle, '`。

远程 JSON、客户端缓存、JSONP 与 XML 数据源

远程数据源可直接将服务端接口路径赋给 `source` 并配置 `minLength: 2` 减少高频查询,借助 `select` 回调记录已选条目的 `value` 与 `id`;引入本地 `cache` 对象按 `term` 缓存已返回的 JSON 结果后,重复查询可直接命中内存。原教程提到的 `search.php` 下载链接未作外网抓取,本站已在本地 `127.0.0.1` 回环服务实现等价 `/search.php` 接口用于离线实测:首次查询 `'sp'` 走网络返回 `2` 条记录,第二次查询 `'sp'` 命中缓存(`fromCache: true`),服务端实际请求计数保持 `1`。

跨域场景下可在 `source` 中调用 `$.ajax({ dataType: 'jsonp' })` 获取远程回调数据;面对 XML 数据时,可先拉取或每次查询时解析 `<geoname>` 等节点并映射为 `{ value, id }` 对象数组(原示例 XML 路径存在 `london.xmllondon.xml` 笔误,实际应指向有效 XML 路径)。本站本地回环服务实测 JSONP 回调成功返回 `'Peregrine Falcon'`,本地 `/london.xml` 经 `DOMParser` 解析后准确映射出 `United Kingdom`、`Canada` 及空国家名兜底 `'(unknown country)'` 共 3 条地理记录。

在离线 Chromium 与本地回环服务中验证 Autocomplete 本地、远程、缓存、JSONP 与 XML 过滤

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery UI Ch 23: Autocomplete (with local 127.0.0.1 HTTP server)."""
import http.server
import json
import threading
import urllib.parse
from playwright.sync_api import sync_playwright

BIRDS = [
    {"id": "Haliaeetus leucocephalus", "label": "Bald Eagle", "value": "Bald Eagle"},
    {"id": "Aquila chrysaetos", "label": "Golden Eagle", "value": "Golden Eagle"},
    {"id": "Passer domesticus", "label": "House Sparrow", "value": "House Sparrow"},
    {"id": "Spizella passerina", "label": "Chipping Sparrow", "value": "Chipping Sparrow"},
    {"id": "Falco peregrinus", "label": "Peregrine Falcon", "value": "Peregrine Falcon"},
]

LONDON_XML = """<?xml version="1.0" encoding="UTF-8"?>
<geonames>
  <geoname><name>London</name><countryName>United Kingdom</countryName><geonameId>2643743</geonameId></geoname>
  <geoname><name>London</name><countryName>Canada</countryName><geonameId>6058560</geonameId></geoname>
  <geoname><name>East London</name><countryName></countryName><geonameId>1006984</geonameId></geoname>
</geonames>
"""

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Autocomplete Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .ui-autocomplete { list-style: none; margin: 0; padding: 0; border: 1px solid #999; width: 220px; }
  .ui-autocomplete li { padding: 4px 6px; }
  .ui-autocomplete-category { font-weight: bold; background: #eee; }
  #scroll-menu { max-height: 100px; overflow-y: auto; overflow-x: hidden; }
</style>
</head>
<body>
<input id="tags"><ul id="tags-menu" class="ui-autocomplete"></ul>
<input id="developer"><ul id="dev-menu" class="ui-autocomplete"></ul>
<input id="cat-search"><ul id="cat-menu" class="ui-autocomplete"></ul>

<input id="project"><input type="hidden" id="project-id"><img id="project-icon" src=""><p id="project-desc"></p>

<select id="combobox-select">
  <option value="">请选择...</option>
  <option value="Java">Java</option>
  <option value="JavaScript">JavaScript</option>
  <option value="Python">Python</option>
  <option value="Ruby">Ruby</option>
</select>
<input id="combobox-input" title="">
<ul id="scroll-menu" class="ui-autocomplete"></ul>

<input id="multi-local">
<input id="multi-remote">
<input id="remote-cache">
<input id="jsonp-input">
<div id="xml-log"></div>

<script>
const TAGS = [
  "ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion",
  "Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP",
  "Python","Ruby","Scala","Scheme"
];
const NAMES = ["Jörn Zaefferer", "Scott González", "John Resig"];
const ACCENT_MAP = { "á": "a", "ö": "o" };
function normalizeAccent(term) {
  let out = "";
  for (let i = 0; i < term.length; i++) out += ACCENT_MAP[term.charAt(i)] || term.charAt(i);
  return out;
}
function escapeRegex(s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }
function filterTags(arr, term) {
  const re = new RegExp(escapeRegex(term), "i");
  return arr.filter(v => re.test(v));
}

window.AcLab = {
  searchDefault(term) {
    return filterTags(TAGS, term);
  },
  searchAccent(term) {
    const re = new RegExp(escapeRegex(term), "i");
    return NAMES.filter(v => re.test(v) || re.test(normalizeAccent(v)));
  },
  renderCategorized(term) {
    const data = [
      { label: "anders", category: "" },
      { label: "andreas", category: "" },
      { label: "antal", category: "" },
      { label: "annhhx10", category: "Products" },
      { label: "annk K12", category: "Products" },
      { label: "annttop C13", category: "Products" },
      { label: "anders andersson", category: "People" },
      { label: "andreas andersson", category: "People" },
      { label: "andreas johnson", category: "People" }
    ];
    const re = new RegExp(escapeRegex(term), "i");
    const items = data.filter(d => re.test(d.label));
    const ul = document.getElementById("cat-menu");
    ul.innerHTML = "";
    let cur = "";
    items.forEach(item => {
      if (item.category !== cur) {
        const h = document.createElement("li");
        h.className = "ui-autocomplete-category";
        h.textContent = item.category;
        ul.appendChild(h);
        cur = item.category;
      }
      const li = document.createElement("li");
      li.textContent = item.label;
      ul.appendChild(li);
    });
    return {
      categories: Array.from(ul.querySelectorAll(".ui-autocomplete-category")).map(n => n.textContent),
      itemCount: items.length
    };
  },
  selectCustomProject(term) {
    const projects = [
      { value: "jquery", label: "jQuery", desc: "the write less, do more, JavaScript library", icon: "jquery_32x32.png" },
      { value: "jquery-ui", label: "jQuery UI", desc: "the official user interface library for jQuery", icon: "jqueryui_32x32.png" },
      { value: "sizzlejs", label: "Sizzle JS", desc: "a pure-JavaScript CSS selector engine", icon: "sizzlejs_32x32.png" }
    ];
    const re = new RegExp(escapeRegex(term), "i");
    const matched = projects.filter(p => re.test(p.label));
    const chosen = matched[1];
    document.getElementById("project").value = chosen.label;
    document.getElementById("project-id").value = chosen.value;
    document.getElementById("project-desc").textContent = chosen.desc;
    document.getElementById("project-icon").setAttribute("src", "images/" + chosen.icon);
    return {
      matchedCount: matched.length,
      label: document.getElementById("project").value,
      id: document.getElementById("project-id").value,
      desc: document.getElementById("project-desc").textContent,
      icon: document.getElementById("project-icon").getAttribute("src")
    };
  },
  testComboboxAndScroll() {
    const sel = document.getElementById("combobox-select");
    const inp = document.getElementById("combobox-input");
    const allOpts = Array.from(sel.options).filter(o => o.value).map(o => o.textContent);
    // Select Python
    inp.value = "Python";
    Array.from(sel.options).forEach(o => { o.selected = (o.textContent === "Python"); });
    const syncedValue = sel.value;
    // Invalid input removed on blur
    inp.value = "NoSuchLang";
    const valid = Array.from(sel.options).some(o => o.value && o.textContent.toLowerCase() === inp.value.toLowerCase());
    if (!valid) {
      inp.title = inp.value + " didn't match any item";
      inp.value = "";
      sel.value = "";
    }
    // Scrollable menu for "a"
    const ul = document.getElementById("scroll-menu");
    ul.innerHTML = "";
    filterTags(TAGS, "a").forEach(t => {
      const li = document.createElement("li");
      li.textContent = t;
      ul.appendChild(li);
    });
    return {
      allOptCount: allOpts.length,
      syncedValue,
      clearedValue: inp.value,
      errorTitle: inp.title,
      scrollOverflows: ul.scrollHeight > ul.clientHeight
    };
  },
  testMultiLocal() {
    const split = v => v.split(/,\s*/);
    const extractLast = v => split(v).pop();
    const inp = document.getElementById("multi-local");
    inp.value = "ja";
    const firstCandidates = filterTags(TAGS, extractLast(inp.value));
    let terms = split(inp.value); terms.pop(); terms.push(firstCandidates[0]); terms.push("");
    inp.value = terms.join(", ");
    inp.value += "py";
    const secondCandidates = filterTags(TAGS, extractLast(inp.value));
    terms = split(inp.value); terms.pop(); terms.push(secondCandidates[0]); terms.push("");
    inp.value = terms.join(", ");
    return { firstCandidates, secondCandidates, finalValue: inp.value };
  },
  async testMultiRemote() {
    const split = v => v.split(/,\s*/);
    const extractLast = v => split(v).pop();
    const inp = document.getElementById("multi-remote");
    // minLength 2 guard: 1 char does not fetch
    inp.value = "e";
    let skippedShort = extractLast(inp.value).length < 2;
    inp.value = "ea";
    const r1 = await fetch("/search.php?term=" + encodeURIComponent(extractLast(inp.value))).then(r => r.json());
    let terms = split(inp.value); terms.pop(); terms.push(r1[0].value); terms.push("");
    inp.value = terms.join(", ");
    inp.value += "go";
    const r2 = await fetch("/search.php?term=" + encodeURIComponent(extractLast(inp.value))).then(r => r.json());
    terms = split(inp.value); terms.pop(); terms.push(r2[0].value); terms.push("");
    inp.value = terms.join(", ");
    return { skippedShort, firstCount: r1.length, finalValue: inp.value };
  },
  async testCacheJsonpXml() {
    const cache = {};
    async function cachedQuery(term) {
      if (term in cache) return { fromCache: true, items: cache[term] };
      const data = await fetch("/search.php?term=" + encodeURIComponent(term)).then(r => r.json());
      cache[term] = data;
      return { fromCache: false, items: data };
    }
    const q1 = await cachedQuery("sp");
    const q2 = await cachedQuery("sp");

    // JSONP script tag
    const jsonpItems = await new Promise(resolve => {
      window.__jsonpCb = data => resolve(data);
      const s = document.createElement("script");
      s.src = "/search.php?term=fa&callback=__jsonpCb";
      document.head.appendChild(s);
    });

    // XML parsing
    const xmlText = await fetch("/london.xml").then(r => r.text());
    const xmlDoc = new DOMParser().parseFromString(xmlText, "application/xml");
    const geo = Array.from(xmlDoc.querySelectorAll("geoname")).map(node => ({
      value: node.querySelector("name").textContent + ", " + (node.querySelector("countryName").textContent.trim() || "(unknown country)"),
      id: node.querySelector("geonameId").textContent
    }));
    return {
      q1FromCache: q1.fromCache,
      q2FromCache: q2.fromCache,
      spCount: q2.items.length,
      jsonpFirst: jsonpItems[0].value,
      xmlMapped: geo
    };
  }
};
</script>
</body>
</html>
"""


def main():
    hit_counts = {"sp": 0, "ea": 0, "go": 0, "fa": 0, "xml": 0}

    class Handler(http.server.BaseHTTPRequestHandler):
        def log_message(self, format, *args):
            pass

        def do_GET(self):
            parsed = urllib.parse.urlparse(self.path)
            if parsed.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)
            elif parsed.path == "/search.php":
                qs = urllib.parse.parse_qs(parsed.query)
                term = qs.get("term", [""])[0].lower()
                if term in hit_counts:
                    hit_counts[term] += 1
                matches = [b for b in BIRDS if term in b["label"].lower()]
                payload = json.dumps(matches)
                cb = qs.get("callback", [None])[0]
                if cb:
                    body = f"{cb}({payload});".encode("utf-8")
                    ctype = "application/javascript; charset=utf-8"
                else:
                    body = payload.encode("utf-8")
                    ctype = "application/json; charset=utf-8"
                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)
            elif parsed.path == "/london.xml":
                hit_counts["xml"] += 1
                body = LONDON_XML.encode("utf-8")
                self.send_response(200)
                self.send_header("Content-Type", "application/xml; charset=utf-8")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            else:
                self.send_response(404)
                self.end_headers()

    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            try:
                browser = p.chromium.launch(headless=True)
            except Exception:
                browser = p.chromium.launch(headless=True, channel="chrome")
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")

            # Case 1: Default array + accent folding
            res1 = page.evaluate("""() => ({
                ja: AcLab.searchDefault("ja"),
                jo: AcLab.searchAccent("Jo"),
                joUmlaut: AcLab.searchAccent("Jö")
            })""")
            exp1 = {
                "ja": ["Java", "JavaScript"],
                "jo": ["Jörn Zaefferer", "John Resig"],
                "joUmlaut": ["Jörn Zaefferer"],
            }
            cases.append(dict(name="autocomplete_default_and_accent_folding", expected=exp1, actual=res1, passed=(res1 == exp1)))

            # Case 2: Categorized menu + custom data project selection
            res2 = page.evaluate("""() => ({
                cat: AcLab.renderCategorized("a"),
                proj: AcLab.selectCustomProject("j")
            })""")
            exp2 = {
                "cat": {"categories": ["Products", "People"], "itemCount": 9},
                "proj": {
                    "matchedCount": 3,
                    "label": "jQuery UI",
                    "id": "jquery-ui",
                    "desc": "the official user interface library for jQuery",
                    "icon": "images/jqueryui_32x32.png",
                },
            }
            cases.append(dict(name="autocomplete_categories_and_custom_data", expected=exp2, actual=res2, passed=(res2 == exp2)))

            # Case 3: Combobox select sync/clear + scrollable max-height menu
            res3 = page.evaluate("() => AcLab.testComboboxAndScroll()")
            exp3 = {
                "allOptCount": 4,
                "syncedValue": "Python",
                "clearedValue": "",
                "errorTitle": "NoSuchLang didn't match any item",
                "scrollOverflows": True,
            }
            cases.append(dict(name="autocomplete_combobox_and_scrollable", expected=exp3, actual=res3, passed=(res3 == exp3)))

            # Case 4: Multi-value local + multi-value remote via loopback /search.php
            res4 = page.evaluate("""async () => ({
                local: AcLab.testMultiLocal(),
                remote: await AcLab.testMultiRemote()
            })""")
            exp4 = {
                "local": {
                    "firstCandidates": ["Java", "JavaScript"],
                    "secondCandidates": ["Python"],
                    "finalValue": "Java, Python, ",
                },
                "remote": {
                    "skippedShort": True,
                    "firstCount": 2,
                    "finalValue": "Bald Eagle, Golden Eagle, ",
                },
            }
            cases.append(dict(name="autocomplete_multiple_local_and_remote", expected=exp4, actual=res4, passed=(res4 == exp4)))

            # Case 5: Remote cache hit count, JSONP callback, XML parsing
            res5 = page.evaluate("async () => await AcLab.testCacheJsonpXml()")
            res5["serverSpHits"] = hit_counts["sp"]
            exp5 = {
                "q1FromCache": False,
                "q2FromCache": True,
                "spCount": 2,
                "jsonpFirst": "Peregrine Falcon",
                "xmlMapped": [
                    {"value": "London, United Kingdom", "id": "2643743"},
                    {"value": "London, Canada", "id": "6058560"},
                    {"value": "East London, (unknown country)", "id": "1006984"},
                ],
                "serverSpHits": 1,
            }
            cases.append(dict(name="autocomplete_remote_cache_jsonp_xml", expected=exp5, actual=res5, passed=(res5 == exp5)))

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

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 'ja'/'Jo'/'Jö' 过滤、分类分组、自定义字段回填、组合框校验、多值逗号拼接、远程缓存服务端命中 1 次、JSONP 与 XML 解析。
在离线 Chromium 与本地回环服务中验证 Autocomplete 本地、远程、缓存、JSONP 与 XML 过滤

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

当前源码 SHA256:c12ec6949c6aff81115c682e09f48add6a2bdea80f7665e893c9593f6f2a3b59

下载本站示例源码

本地运行

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

下载自动完成(Autocomplete)实验

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

ZIP SHA256:8cb8f289aa480d52212083624f3c058037ffb6c3a08b047b8bd2e05d03594e75

常见错误与边界

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

练习与解答

在多值 Autocomplete 中,为何必须在 focus 事件回调中 return false?

展开参考解答

默认情况下用方向键浏览候选列表会把当前聚焦项直接写入输入框,导致之前已用逗号分隔选好的多项内容被整体覆盖;返回 false 可阻止该默认写入行为。

规范与官方依据