jQuery UI Combobox 在 IE10 環境下啟用 multiple: true 時會拋出 indexOf is not a function 錯誤。本文分析根因並提供兩種修正方案。
// jQuery UI 內部原始碼片段 (約 10650 行)
function _7e8(_7e9, _7ea) {
var _7eb = $.data(_7e9, "combobox");
var opts = _7eb.options;
var _7ec = $(_7e9).combo("getValues"); // 回傳陣列
var _7ed = _7ec.indexOf(_7ea + ""); // ❌ IE10 陣列無 indexOf 方法
if (_7ed >= 0) {
_7ec.splice(_7ed, 1);
_7e7(_7e9, _7ec);
}
}
Array.prototype.indexOf 是 ES5 新增方法indexOf 未做 polyfill 防護找到錯誤行所在檔案(通常是 jquery.ui.combobox.js 或打包後的 jquery-ui.js),將 indexOf 呼叫替換為相容寫法:
// 原始碼
var _7ed = _7ec.indexOf(_7ea + "");
// 修改為:手動實作 indexOf 邏輯
var _7ed = (function(arr, str) {
str = str + "";
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] == str) return i;
}
return -1;
})(_7ec, _7ea);
在頁面載入最早期(所有腳本之前)引入:
<script>
// Array.prototype.indexOf Polyfill (MDN 標準實作)
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
if (this == null) throw new TypeError('"this" is null or not defined');
const o = Object(this);
const len = o.length >>> 0;
if (len === 0) return -1;
const n = fromIndex | 0;
let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) return k;
k++;
}
return -1;
};
}
// 同理補上 forEach, filter, map, reduce 等 ES5 陣列方法
if (!Array.prototype.forEach) { /* ... */ }
if (!Array.prototype.filter) { /* ... */ }
</script>
jQuery UI 已停止維護(2021 宣布結束),建議遷移至現代替代方案:
| 庫 | 特色 | 多選支援 | 體積 |
|---|---|---|---|
| Select2 | 成熟、功能豐富、主題化 | 內建 multiple: true | ~20KB gz |
| Choices.js | 無 jQuery 依賴、ES6 模組化 | 原生支援 | ~15KB gz |
| Tom Select | Selectize 分支、無依賴、效能佳 | 原生支援 | ~12KB gz |
| Vue Select / React Select | 框架整合、TypeScript 支援 | 第一類公民 | 視框架 |
<!-- HTML -->
<select id="multiSelect" multiple="multiple" style="width: 100%">
<option value="1">選項 1</option>
<option value="2">選項 2</option>
<option value="3">選項 3</option>
</select>
<!-- JS -->
$('#multiSelect').select2({
placeholder: '請選擇...',
allowClear: true,
closeOnSelect: false, // 多選時不自動關閉
tags: true // 允許輸入新標籤
});
// 取值
$('#multiSelect').val(); // ['1', '3']
// 設值
$('#multiSelect').val(['1', '2']).trigger('change');
<script>
// 測試 indexOf 相容性
console.log([1,2,3].indexOf(2)); // 1
console.log(['a','b'].indexOf('c')); // -1
// 測試 Combobox 多選
$('#combobox').combobox({ multiple: true });
$('#combobox').combobox('setValues', ['1', '3']);
console.log($('#combobox').combobox('getValues')); // ['1', '3']
</script>