举个例子。如果有一个选项是“Eyes Nose”,那么我想搜索输入为“Ey No”的选项。 Select2 无法在此处建议该选项。
默认情况下,如果我们只是搜索输入“Ey”或“No”,那么该选项将被显示,但是只要在搜索时没有遵循字母序列(比如我输入像这样的空格“Ey”)然后select2 搜索建议不起作用。
我知道通过修改 select2 的 matcher() 函数,可以做到这一点。我做不到。
例如: 我有简单的选择选项:
<select>
<option id="1">Mouth</option>
<option id="2">Head</option>
<option id="3">Eyes Nose</option>
</select>
我想在这里搜索关键字“Ey No”,它应该显示 id=3 的选项,即“Eyes Nose”。
我找到了一个有效的解决方案。
matcher: function(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;
}
var words = params.term.toUpperCase().split(" ");
for (var i = 0; i < words.length; i++) {
if (data.text.toUpperCase().indexOf(words[i]) < 0) {
return null;
}
}
return data;
}
版本问题。匹配器参数已更改,上面的代码现在适用于 select2 最新版本。该解决方案有助于在搜索栏中使用部分单词搜索选择选项。