对于只能选择一个选项的下拉选择框,会自动在下拉菜单顶部添加一个搜索框。可以使用 Select2 轻松自定义搜索框的行为和外观。
当用户通过在搜索框中输入搜索词来筛选结果时,Select2 使用内部的“匹配器”将搜索词与结果进行匹配。您可以通过为 matcher 指定一个回调函数来自定义 Select2 匹配搜索词的方式。matcher
配置选项分配自定义适配器来覆盖选择适配器。
Select2 会将每个选项以其内部表示形式传入此回调函数以确定是否应显示该选项:
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.indexOf(params.term) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += ' (matched)';
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-matcher").select2({
matcher: matchCustom
});
matcher
仅适用于本地提供的数据(例如,通过数组! 当使用远程数据集时,Select2 希望返回的结果已经在服务器端进行了过滤。
只有第一层对象会被传递给matcher
回调函数。如果您处理的是嵌套数据,则必须遍历children
数组并单独对它们进行匹配。这允许在处理嵌套对象时进行更高级的匹配,您可以按照自己的需求处理它们。
此示例仅在字符串开头包含搜索词时才匹配结果:
A 兼容性模块提供了用于使用 v3 风格匹配器回调的功能。
有时在处理大型数据集时,只有当搜索词达到一定长度时才开始过滤结果会更加高效。在处理远程数据集时这种情况非常常见,因为它只允许使用重要的搜索词。
您可以通过使用minimumInputLength
选项下的选项:
$('select').select2({
minimumInputLength: 3 // only start searching when the user has input 3 or more characters
});
在某些情况下,需要将搜索词限制在一定范围内。Select2 允许您限制搜索词的长度,确保其不超过特定长度。
您可以通过使用maximumInputLength
选项下的选项:
$('select').select2({
maximumInputLength: 20 // only allow terms up to 20 characters long
});
的minimumResultsForSearch
选项用于确定下拉菜单初始填充时所需的最小结果数量,以显示搜索框。
此选项适用于使用本地数据且结果集较小的情况,此时搜索框只会浪费屏幕空间。将此值设置为 -1 可以永久隐藏搜索框。
$('select').select2({
minimumResultsForSearch: 20 // at least 20 results must be displayed
});
对于单选下拉框,Select2 允许您使用minimumResultsForSearch
配置选项隐藏搜索框。在此示例中,我们使用值Infinity
来告诉 Select2 永远不要显示搜索框。
对于多选框,没有独立的搜索控件。因此,要禁用多选框的搜索功能,在每次打开或关闭下拉菜单时都需要将disabled
属性设置为 true:
参见此问题查看此解决方案的来源。