javascript-Select2-搜索通配符匹配
作者:互联网
我正在使用Select2设置选择框的样式并添加功能,我想知道如何使搜索规则更宽松.当前,如果下拉列表中有“新墨西哥”,我可以搜索“墨西哥”或“新墨西哥”以匹配选择选项,但是如果输入“新墨西哥”,则会得到“未找到结果”.有没有一种方法可以扩展搜索功能以匹配搜索词而不管它们的顺序如何?
$(document).ready(function() {
$(".states").select2();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="states" style="width: 50%">
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="TB">Tshirt, Black</option>
</select>
解决方法:
好了,显然您可以设置custom matchers来完成此操作.我发现this one,并且似乎按预期工作:
$(function () {
$('.states').select2({
matcher: function (params, data) {
if ($.trim(params.term) === '') {
return data;
}
keywords=(params.term).split(" ");
for (var i = 0; i < keywords.length; i++) {
if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1)
return null;
}
return data;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="states" style="width: 50%">
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="TB">Tshirt, Black</option>
</select>
标签:select2,javascript 来源: https://codeday.me/bug/20191013/1910704.html