<div class="control-nationality-suggest">
<input type="text" class="nationality-suggest-input" placeholder="輸入中文/英文/代碼搜尋" autocomplete="off" aria-autocomplete="list" aria-controls="nationality-list" />
<div class="nationality-suggest-list-container" hidden>
<div class="nationality-suggest-hint">輸入關鍵字或 ↑↓ 選擇</div>
<ul class="nationality-suggest-list" id="nationality-list" role="listbox"></ul>
</div>
</div>
將陣列扁平化為單一字串,利用正則一次匹配,比迴圈快數倍:
// 原始資料
const raw = [
{ id: 'CN', en: 'China', cn: '中國大陸' },
{ id: 'HK', en: 'Hong Kong', cn: '中國香港' },
{ id: 'MO', en: 'Macau', cn: '中國澳門' },
{ id: 'TW', en: 'Taiwan', cn: '中國台灣' }
// ... 200+ 筆
];
// 扁平化:#CN|China|中國大陸##HK|Hong Kong|中國香港##...
const FLAT = '#' + raw.map(d => `${d.id}|${d.en}|${d.cn}`).join('##') + '#';
// 搜尋函式
function search(key) {
if (!key) return raw.slice(0, 10); // 預設顯示前 10
const regex = new RegExp(`#[^#]*?${escapeRegExp(key)}[^#]*?#`, 'gi');
const matches = FLAT.match(regex) || [];
return matches.map(m => {
const [, id, en, cn] = m.match(/#([^|]+)\|([^|]+)\|([^#]+)#/);
return { id, en, cn };
}).slice(0, 50); // 限制顯示筆數
}
function escapeRegExp(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
class NationalitySelect {
constructor(container) {
this.$container = $(container);
this.$input = this.$container.find('.nationality-suggest-input');
this.$list = this.$container.find('.nationality-suggest-list');
this.$wrapper = this.$container.find('.nationality-suggest-list-container');
this.data = raw; // 外部注入
this.flat = FLAT;
this.selectedIndex = -1;
this.bindEvents();
}
bindEvents() {
this.$input.on('input', e => this.onInput(e.target.value));
this.$input.on('keydown', e => this.onKeydown(e));
this.$input.on('focus', () => this.open());
this.$list.on('click', 'li', e => this.select($(e.currentTarget).data('item')));
$(document).on('click', e => { if (!this.$container.is(e.target) && this.$container.has(e.target).length === 0) this.close(); });
}
onInput(val) {
this.results = search(val);
this.renderList();
this.open();
}
onKeydown(e) {
if (!this.$wrapper.is(':visible')) return;
if (e.key === 'ArrowDown') { this.moveSelection(1); e.preventDefault(); }
else if (e.key === 'ArrowUp') { this.moveSelection(-1); e.preventDefault(); }
else if (e.key === 'Enter') { this.confirm(); e.preventDefault(); }
else if (e.key === 'Escape') { this.close(); }
}
moveSelection(dir) {
const len = this.results.length;
if (!len) return;
this.selectedIndex = (this.selectedIndex + dir + len) % len;
this.$list.find('li').removeClass('active').eq(this.selectedIndex).addClass('active')[0].scrollIntoView({ block: 'nearest' });
}
confirm() {
if (this.selectedIndex >= 0) this.select(this.results[this.selectedIndex]);
}
select(item) {
this.$input.val(`${item.cn} (${item.id})`).data('selected', item);
this.close();
this.$input.trigger('change', [item]); // 觸發自訂事件
}
renderList() {
this.$list.empty();
this.results.forEach((item, i) => {
const $li = $(`<li role="option">${item.cn} / ${item.en} (${item.id})</li>`).data('item', item);
if (i === this.selectedIndex) $li.addClass('active');
this.$list.append($li);
});
this.selectedIndex = -1;
}
open() { this.$wrapper.show(); }
close() { this.$wrapper.hide(); }
}
// 初始化所有實例
$('.control-nationality-suggest').each((i, el) => new NationalitySelect(el));
.nationality-suggest-list-container { position: absolute; z-index: 100; width: 100%; max-height: 240px; overflow-y: auto; border: 1px solid #ddd; background: #fff; box-shadow: 0 4px 12px rgba(0,0,0,.1); }
.nationality-suggest-list { margin: 0; padding: 0; list-style: none; }
.nationality-suggest-list li { padding: 8px 12px; cursor: pointer; }
.nationality-suggest-list li.active { background: #e8f0fe; color: #1a73e8; }
.nationality-suggest-hint { padding: 8px 12px; color: #666; font-size: 12px; border-bottom: 1px solid #eee; }
indexOf,實測 200 筆資料 < 1ms。scroll 動態替換 DOM。input 事件加 100-150ms debounce 避免頻繁渲染。國籍選擇器核心在於「多欄位快速過濾」與「鍵盤無障礙操作」。扁平化字串 + 正則搜尋是輕量級高效能方案;大數據量時轉向虛擬列表。元件化封裝後可輕鬆複用於表單、後台管理等場景。