在文本中间自动完成(例如Google Plus)

Chr*_*ois 11 jquery autocomplete jquery-ui-autocomplete google-plus

有很多选择可以做自动完成.他们中的大多数似乎都在输入的前几个字母上工作.

在Google Plus中,自动填充选项在输入后很快就会下降@,无论它在表单字段中出现在何处,并使用紧随其后的字母@来指导自动填充.(它看起来也很不错!)

有没有人共享代码来做这种事情?

有没有人有任何指针试图实现这个玩具版本(例如在jQuery中)?

And*_*ker 17

这可以通过jQueryUI的自动完成小部件实现.具体来说,您可以调整此演示以满足您的要求.这是一个例子:

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

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

var availableTags = [ ... ]; // Your local data source.

$("#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 (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            }
        }
        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;
    }
});
Run Code Online (Sandbox Code Playgroud)

它在这里工作:http://jsfiddle.net/UdUrk/

如果您需要更多信息(例如如何使其与远程数据源一起使用),请告诉我.

更新:这是使用远程数据源(StackOverflow的API)的示例:http://jsfiddle.net/LHNky/.它还包括自动填充建议的自定义显示.