根据匹配位置对自动填充UI结果进行排序 [英] Sorting Autocomplete UI Results based on match location

查看:91
本文介绍了根据匹配位置对自动填充UI结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据匹配发生在字符串中的位置对jQuery Autocomplete UI结果进行排序.匹配是第一个字母的结果应优先于匹配在字符串中间的结果.

I'd like to sort my jQuery Autocomplete UI results based on where in the string the match occurs. The results where the match is the first letter should be prioritized above results in which the match is in the middle of the string.

搜索"M"应返回:

马特,迈克尔,山姆,蒂姆,亚当,本杰明

Matt, Michael, Sam, Tim, Adam, Benjamin

相反,由于它现在只是按字母顺序返回项目,所以我得到了:

Instead, since it's just returning the items in alphabetical order right now, I'm getting this:

亚当,本杰明,马特,迈克尔,山姆,蒂姆

Adam, Benjamin, Matt, Michael, Sam, Tim

不幸的是,看起来自动完成"用户界面没有执行此操作的任何选项,而是按照接收到的顺序显示结果.让MySql进行排序不是一种选择,因为所有可能的匹配都已预先加载,因此我不会在每次击键时都对数据库进行调用.有人做过这样的事吗?

Unfortunately, it looks like Autocomplete UI doesn't have any options for doing something like this, instead it just presents the results in the order it received them. Having MySql do the sorting isn't an option since all the possible matches are preloaded so that I'm not making calls to the database with every keystroke. Has anybody done anything like this?

推荐答案

您可以通过为source选项提供函数而不是简单数组来提供所需的任何本地过滤逻辑.这是一个简单的示例,它将满足您所需的基础知识:

You can provide any local filtering logic you'd like by providing the source option a function instead of a simple array. Here's a quick example that will do the basics of what you want:

var source = ['Adam', 'Benjamin', 'Matt', 'Michael', 'Sam', 'Tim'];
$("input").autocomplete({
    source: function (request, response) {
        var term = $.ui.autocomplete.escapeRegex(request.term)
            , startsWithMatcher = new RegExp("^" + term, "i")
            , startsWith = $.grep(source, function(value) {
                return startsWithMatcher.test(value.label || value.value || value);
            })
            , containsMatcher = new RegExp(term, "i")
            , contains = $.grep(source, function (value) {
                return $.inArray(value, startsWith) < 0 &&
                    containsMatcher.test(value.label || value.value || value);
            });

        response(startsWith.concat(contains));
    }
});

示例: http://jsfiddle.net/zkVrs/

基本上,逻辑是建立一个以该词开头的匹配项数组,然后将其与包含该词但不以该词开头的匹配项连接起来.

Basically, the logic is to build up an array of matches that start with the term, and then concatenate that with matches that contain the term but don't start with it.

这里的性能可能是个问题,尤其是对于$.inArray调用.可能是完成此部分的更好方法,但希望这会为您提供一个良好的起点.

Performance could be a problem here, especially with the $.inArray call. Might be a better way to accomplish that portion, but hopefully that will give you a good starting point.

这篇关于根据匹配位置对自动填充UI结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆