我有一个用于手机国家/地区代码的 select2 下拉列表。
id
值适用于实际的国家/地区代码,例如+1、+61、+86 等,下拉列表的 text
值配置为 ${countryCode} (${countryTwoLetterCode})
,例如+1(美国)
问题是用户只能搜索 select2 的
text
部分。有没有一种方法可以添加隐藏的可搜索值,即完整的国家/地区名称,这样如果我搜索字符串 United 那么它将显示美国和英国的结果,即 +1(美国)和 +44(GB)
这就是 select2 数据格式的样子,基于他们的[文档][1]
{
"results": [
{
"id": 1,
"text": "Option 1"
}
]
}
[1]: https://select2.org/data-sources/formats
好吧,所以我想我找到了一个解决方案,方法是在初始化期间在 select2 的
data
对象中添加一个新属性,这样对象列表将像这样
[
{
id: '+44',
text: '+44 (GB)',
dataValue: 'United Kingdom'
},
{
id: '+1',
text: '+1 (US)',
dataValue: 'United States'
}
]
当我们实现
自定义匹配器时,将使用新属性
dataValue
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (typeof data.dataValue === 'undefined') {
return null;
}
if (data.text.toLowerCase().includes(params.term.toLowerCase())) {
return data;
}
if (data.dataValue.toLowerCase().includes(params.term.toLowerCase())) {
return data;
}
return null;
}
最后,自定义匹配器函数将包含在 select2 初始化中。
$('#country-code-dropdown').select2({
data: data,
matcher: matchCustom
});