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

时间:2023-03-27
本文介绍了实现 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.

希望对您有所帮助.

这篇关于实现 jquery UI 自动完成以在您键入“@"时显示建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:带有 jQ​​uery 的饼图 下一篇:document.ready 和 $function 的区别

相关文章

最新文章