为非相邻关键字选择2自定义匹配器

AV8*_*6NL 4 javascript jquery-select2

我在我的应用程序中使用Select2以允许搜索大约1200个选项的下拉列表.

我目前正在使用Select2的匹配器的默认实现,只要关键字在搜索结果中相邻,它就可以正常工作:

function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }
Run Code Online (Sandbox Code Playgroud)

例如,搜索'stackoverflow question'会返回选项'Stackoverflow关于Select2的问题'

然而,我会希望匹配器根据非相邻关键字返回结果.例如,我也希望它在搜索'stackoverflow select2'时返回上面的选项.

是否有人知道如何创建自定义匹配器以允许此行为?

Yur*_*ray 9

这就是我在Select2 4中所做的.我希望匹配器只返回包含所有输入关键字的选项(假设关键字是由""拆分的搜索词).匹配是案例性的.

        matcher: function (params, data) {
                // If there are no search terms, return all of the data
                if ($.trim(params.term) === '') {
                    return data;
                }
                // `params.term` should be the term that is used for searching
                // split by " " to get keywords
                keywords=(params.term).split(" ");
                // `data.text` is the text that is displayed for the data object
                // check if data.text contains all of keywords, if some is missing, return null
                for (var i = 0; i < keywords.length; i++) {

                    if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1) 
                      // Return `null` if the term should not be displayed
                      return null;

                }
                // If here, data.text contains all keywords, so return it.
                return data;
            }
Run Code Online (Sandbox Code Playgroud)

我知道这是一个老话题,但也许有人觉得这很有用.


Val*_*jon 1

尝试这个:

搜索Stackoverflow 问题stackoverflow select2select2 stackoverflow关于 stackoverflow select2 问题关于 select2 的问题

<select id="e17_2" style="width:300px">
   <option alt="Stackoverflow question about Select2">Stackoverflow question about Select2</option>
   <option alt="Stackoverflow Other line ...">Stackoverflow Other line ...</option>
</select>
Run Code Online (Sandbox Code Playgroud)

复制自:https ://stackoverflow.com/a/21745151/3710490

function permute(input, permArr, usedChars) {
    var i, ch;
    for (i = 0; i < input.length; i++) {
        ch = input.splice(i, 1)[0];
        usedChars.push(ch);
        if (input.length == 0) {
            permArr.push(usedChars.slice());
        }
        permute(input, permArr, usedChars);
        input.splice(i, 0, ch);
        usedChars.pop();
    }
    return permArr
};


$("#e17_2").select2({
    matcher: function(term, text) { 

                if (term.length == 0) return true;
                texts = text.split(" ");

                allCombinations = permute(texts, [], []);

                for(i in allCombinations){
                    if( allCombinations[i].join(" ").toUpperCase().indexOf(term.toUpperCase())==0 ){
                        return true;
                    }
                }

                return false;

    }
});
Run Code Online (Sandbox Code Playgroud)