首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery UI自动搜索以搜索多个字符串

jQuery UI自动搜索以搜索多个字符串
EN

Stack Overflow用户
提问于 2012-06-22 07:04:03
回答 1查看 238关注 0票数 2

我需要向jQuery UI自动搜索功能添加一些功能。我想要解决的问题是允许用户以任何顺序输入文本,这些文本将在术语列表中进行搜索并显示建议。例如,假设我有以下术语:

代码语言:javascript
复制
the brown cow jumped over the moon
the blue cow watched in horror
the red cow simply laughed 
the green cow got sick at such a sight
the yellow cow lost 5 bucks to the black cow
the black cow smiled at his fortune

If the user types in "the cow", I would expect the autocomplete feature to list all the results.
If I type in "brown moon", I would expect the first result to appear.
If I type in "fortune smiled", the last result would appear.

基本上,此行为允许用户以任何顺序键入任何字符串并获得搜索结果。

我是这么想的。我需要在"open“或"search”事件中添加一个回调函数,并在那里操作结果。到目前为止,我的代码如下:

代码语言:javascript
复制
$(function ()
{
    var data =
    [
        "the brown cow jumped over the moon",
        "the blue cow watched in horror",
        "the red cow simply laughed ",
        "the green cow got sick at such a sight",
        "the yellow cow lost 5 bucks to the black cow",
        "the black cow smiled at his fortune"
    ];

    $(".text-search").autocomplete(
    {
        autoFocus: true,
        source: data,
        delay: 0,
        minLength: 2,
        open: function (e, ui)
        {
            debugger;
            // what should i do here?
        },
        search: function (e, ui)
        {
            debugger;
            // what should i do here?
        }
    });
});

<div class="ui-widget">
    <label for="autocomplete">Autocomplete: </label>
    <input class="text-search">
</div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-22 07:48:15

我会根据用户输入的文本创建您自己的正则表达式。然后,您可以使用此正则表达式来测试候选列表中的每个项目:

代码语言:javascript
复制
$(".text-search").autocomplete({
    autoFocus: true,
    source: function(request, response) {
        var regexStr = "\\b(" + $.map($.trim(request.term).split(" "), function(term) {
            return $.ui.autocomplete.escapeRegex($.trim(term))
        }).join("|") + ")\\b",
        matcher = new RegExp(regexStr);

        response($.grep(data, function(value) {
            return matcher.test(value.label || value.value || value);
        }));
    },
    delay: 0,
    minLength: 2
});

正则表达式看起来很神秘,但它只是使用交替(|)生成一个表达式。例如,如果您键入brown cow,将生成\b(brown|cow)\b,它将匹配带有"brown“或"cow”的任何字符串。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11148055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档