2

jQueryUI自動検索機能にいくつかの機能を追加する必要があります。私が解決したい問題は、ユーザーが用語のリストを検索して提案を表示する任意の順序でテキストを入力できるようにすることです。たとえば、次の用語があるとします。

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」イベントのいずれかにコールバック関数を追加し、そこで結果を操作する必要があります。これまでの私のコードは次のとおりです。

$(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 に答える