Select2 - 搜索通配符匹配项

Select2 - Searching wildcard matches

我正在使用 Select2 来设计我的 select 框并添加功能,我想知道如何使搜索规则更宽松。目前,如果我在下拉列表中有 "New Mexico",我可以搜索 "mexico" 或 "new mexico" 来匹配 select 选项,但是如果我输入 "mexico new",我会得到 "no results found." 有没有办法扩展搜索功能以匹配搜索词而不考虑它们的顺序?

$(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 to accomplish this. I found 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>