萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現輸入框自動完成:關鍵字聯想、鍵盤導航、AJAX 數據源

自動完成是提升表單輸入效率的關鍵組件。本文解析一個完整的 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、渲染、鍵盤導航邏輯
};

關鍵功能實現要點

1. 防抖 + 快取

$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);
});

2. 鍵盤導航

$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(); }
});

3. 選中項高亮與同步輸入框

function highlight(index) {
  $items.removeClass('active').eq(index).addClass('active');
  $input.val($items.eq(index).data('value')); // 同步顯示
  selectedIndex = index;
}

4. 位置定位

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、支援基本建議、無法自訂樣式/異步。
  • Tom Select / Choices.js:無 jQuery 依賴、功能豐富、支援標籤、分組、遠端搜尋。
  • Algolia Autocomplete / Downshift:React/Vue 生態首選、無障礙完善、Headless 架構。

理解自動完成內部機制(防抖、快取、鍵盤導航、定位)有助於選型與除錯,即便使用成熟庫也能游刃有餘。

copyright © 萬盛學電腦網 all rights reserved