自動完成是提升表單輸入效率的關鍵組件。本文解析一個完整的 jQuery 自動完成插件架構:資料源抽象、防抖請求、下拉選單渲染、鍵盤導航(上下鍵選擇、Enter 確認)、滑鼠互動、快取機制。
$.Completion = function(settings) {
const opts = $.extend({
$input: null, // 目標輸入框
$dropdown: null, // 下拉容器
dataUrl: '', // AJAX 端點,回傳 JSON 陣列
paramName: 'q', // 查詢參數名
minLength: 1, // 最少觸發字元
maxItems: 10, // 最大顯示筆數
debounce: 200, // 防抖 ms
template: item => item.label || item.value, // 渲染函式
onSelect: null // 選中回調
}, settings);
let cache = new Map(); // 簡易快取
let debounceTimer = null;
let selectedIndex = -1;
// ... 事件綁定、AJAX、渲染、鍵盤導航邏輯
};
$input.on('input', function() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
const q = $input.val().trim();
if (q.length < opts.minLength) return hide();
if (cache.has(q)) return render(cache.get(q));
fetchData(q).then(data => { cache.set(q, data); render(data); });
}, opts.debounce);
});
$input.on('keydown', e => {
const $items = $dropdown.find('li');
if (e.key === 'ArrowDown') { e.preventDefault(); selectNext($items); }
else if (e.key === 'ArrowUp') { e.preventDefault(); selectPrev($items); }
else if (e.key === 'Enter') { e.preventDefault(); confirmSelect(); }
else if (e.key === 'Escape') { hide(); }
});
function highlight(index) {
$items.removeClass('active').eq(index).addClass('active');
$input.val($items.eq(index).data('value')); // 同步顯示
selectedIndex = index;
}
function position() {
const offset = $input.offset();
$dropdown.css({
top: offset.top + $input.outerHeight(),
left: offset.left,
width: $input.outerWidth(),
maxHeight: opts.maxHeight || 300
}).show();
}
<datalist>:零 JS、支援基本建議、無法自訂樣式/異步。理解自動完成內部機制(防抖、快取、鍵盤導航、定位)有助於選型與除錯,即便使用成熟庫也能游刃有餘。