选择2按类型搜索预加载列表

select2 search preloaded list as typed

本文关键字:加载 列表 搜索 类型 选择      更新时间:2023-09-26

我在选择菜单上使用Select2,当用户在搜索字段中输入时,Select2将搜索这些字母并显示它们,即使它们只是出现在选项的中间。例如,如果我有一个这样的选择:

 <select id="e1">
    <option value="apple">Apple</option>
    <option value="grape">Grape</option>
    <option value="prune">Prune</option>
</select>

我的Select2代码是这样的:

$('#e1').select2({
                    placeholder: "",
                    allowClear: true,
                    width: '600px',
                    selectOnBlur: true,
                    scrollpad: true,
                });

用户只需在搜索框中输入"p",它就会显示所有三个选项。在这种情况下,我想让它只显示"修剪"。有什么办法可以做到吗?我在谷歌和文档上看了一下,要么我错过了一些非常重要的东西,要么就是没有。有人对这件事有什么至理名言吗?

您只需要提供一个自定义的matcher设置。

当前默认的匹配器函数:

function(term, text) { 
    return text.toUpperCase().indexOf(term.toUpperCase())>=0;
}
例如,你可以用 来代替它
function(term, text) { 
    return text.substr(0, term.length).toUpperCase() == term.toUpperCase();
}

示例设置:

$("#e1").select2({
    // ...other options...
    matcher: function(term, text) { ... }
});