实现 jquery UI 自动完成以在您键入“@"时显示建议

我正在使用 jquery UI AutoComplete 来允许用户使用@mentions 标记朋友.默认情况下,当您将焦点放在文本框上时,自动完成建议就会出现.如何让建议仅在您键入@"时出现?这是我到目前为止的代码:

I'm using jquery UI AutoComplete to allow users to tag friends using @mentions. By default, the autocomplete suggestions appear when as soon you put focus on the textbox. How can you make the suggestions appear only when you type "@"? This is the code I have so far:

var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            ];
$("#tags").autocomplete({
    source: availableTags,
    minLength: 0
});

推荐答案

您可以通过向自动完成的 source 选项提供一个函数来实现:

You can do this by providing a function to the source option of autocomplete:

var availableTags = [ /* Snip */];

function split(val) {
    return val.split(/@s*/);
}

function extractLast(term) {
    return split(term).pop();
}

$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
        event.preventDefault();
    }
}).autocomplete({
    minLength: 0,
    source: function(request, response) {
        var term = request.term,
            results = [];

        /* If the user typed an "@": */
        if (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            /* If they've typed anything after the "@": */
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            /* Otherwise, tell them to start typing! */
            } else {
                results = ['Start typing...'];
            }
        }
        /* Call the callback with the results: */
        response(results);
    },
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join("");
        return false;
    }
});

这是一个工作示例:http://jsfiddle.net/BfAtM/2/

请注意,这几乎与 此演示相同,除了要求用户键入@".该代码位于 source 选项参数中.

Note that this is almost identical to this demo, except for the requirement for the user to type "@". That code is located inside the source option argument.

希望对您有所帮助.

相关文章