本文介绍了为非相邻关键字选择2自定义匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用,以便搜索包含大约1200个选项的下拉菜单。

I use Select2 in my app to allow for searching a dropdown with about 1200 options.

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

I am currently making use of the default implementation of Select2's matcher, which works well as long as keywords are adjacent in the search results:

function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }

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

For example, a search for 'stackoverflow question' returns option 'Stackoverflow question about Select2'

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

I would however else like the matcher to return results based on non-adjacent keywords. For instance, I would also like it to return the above option when searching for 'stackoverflow select2'.

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

Would anyone have an idea how to create a custom matcher to allow for this behavior?

推荐答案

试试这个:

搜索 Stackoverflow问题 stackoverflow select2 select2 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>

复制自:

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;

    }
});

这篇关于为非相邻关键字选择2自定义匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:58