我想编写一个自定义select2(版本4.0)匹配器,以便在执行搜索时忽略dots
和whitespaces
。
。如果其中一个选项是Dr. R. N. Pandey
,我应该能够通过在搜索框中输入rnp
来找到Dr. R. N. Pandey
。
请试试:
HTML:<select class='select2'>
<option>Select</option>
<optgroup label="Vegetables">
<option>A. Celery</option>
<option>Green R.P Pepper</option>
<option>Kale</option>
</optgroup>
<optgroup label="Fruits">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</optgroup>
<optgroup label="Nuts" disabled>
<option>Almond</option>
<option>Walnut</option>
<option>Pine</option>
</optgroup>
</select>
JS:
(function() {
function matcher(term, text) {
term = term.toUpperCase();
text = text.toUpperCase().replace(/./g, '').replace(/s+/g, '');
if (text.indexOf(term) > -1 ) {
return true;
}
return false;
}
$(".select2").select2({
matcher: matcher
});
})();
请看一下演示(<4.0):
https://jsfiddle.net/xfw4tmbx/22/select 2 version 4.0
https://jsfiddle.net/11a998kw/1/受已有答案启发:
function ignoreDotAndWhitespace(params, data) {
params.term = params.term || '';
term = params.term.toUpperCase();
text = data.text.toUpperCase().replace(/./g, '').replace(/s+/g, '');
if (text.indexOf(term) > -1 ) {
return data;
}
return false;
}
$('.select2').select2({
matcher: function(params, data) {
return ignoreDotAndWhitespace(params, data);
}
});