【问题标题】:Select2 Custom MatcherSelect2 自定义匹配器
【发布时间】:2014-07-12 01:26:20
【问题描述】:

我正在尝试将自定义匹配器与 select2 库一起使用。具体来说,我想返回 other 作为未找到的选项,以及仅从字符串的开头匹配。我发现以下 SO 问题分别回答了这些部分:

Select2, when no option matches, "other" should appear

jquery select2 plugin how to get only the result 'myString%'

但是,当我结合这两种技术时,它不再正确匹配。我的解决方案如下:

$("#myForm").select2({
    minimumInputLength: 2,
    width: width,
    matcher: function(term, text) {
        // THIS IS WHERE I COMBINE THE METHODS
        return text === 'Other' || text.toUpperCase().indexOf(term.toUpperCase())==0;
    },
    sortResults: function(results) {
        if (results.length > 1) results.pop();
            return results;
    }
});

我做错了什么,使这个匹配器功能的正确方法是什么?

【问题讨论】:

    标签: jquery jquery-select2


    【解决方案1】:

    我使用正则表达式并将条件|| 分为两个步骤来完成此操作。最终代码是:

    $("#myForm").select2({
        minimumInputLength: 2,
        width: width,
        matcher: function(term, text) {
            var terms = term.split(" ");
            for (var i=0; i < terms.length; i++){
                var tester = new RegExp("\\b" + terms[i], 'i');
                if (tester.test(text) == false){
                    return (text === 'Other')
                }
            }
            return true;
        },
        sortResults: function(results) {
            if (results.length > 1) {
                results.pop();
            }
            return results;
        },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2015-10-26
      • 2018-03-17
      • 2020-07-07
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多