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

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

问题描述

我想根据匹配出现在字符串中的位置对我的 jQuery 自动完成 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

不幸的是,看起来自动完成 UI 没有执行此类操作的任何选项,它只是按照收到的顺序显示结果.让 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天全站免登陆