Select2 - 搜索通配符匹配

时间:2016-10-21 16:14:17

标签: javascript select2

我正在使用Select2来设置我的选择框并添加功能,我想知道如何使搜索规则更加宽松。目前,如果我在下拉列表中有“新墨西哥”,我可以搜索“墨西哥”或“新墨西哥”以匹配选择选项,但如果我输入“mexico new”,我会“找不到结果”。有没有办法扩展搜索功能以匹配搜索词而不管它们的顺序?

$(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>

1 个答案:

答案 0 :(得分:7)

好吧,显然你可以设置custom matchers来完成这个任务。我找到了this one,它似乎正在按预期工作:

&#13;
&#13;
$(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;
        }
    });
});
&#13;
<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>
&#13;
&#13;
&#13;