2

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

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.

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

这就是我的想法。我需要在“打开”或“搜索”事件中添加一个回调函数并在那里操作结果。到目前为止,这是我的代码:

$(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>
4

1 回答 1

1

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

$(".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/

于 2012-06-21T23:48:15.497 回答