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

我正在使用jquery UI AutoComplete来允许用户使用@mentions标记朋友。 默认情况下,只要您将焦点放在文本框上,就会显示自动填充建议。 只有当您输入“@”时,如何才能显示建议? 这是我到目前为止的代码:

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

您可以通过为自动完成的source选项提供一个函数来完成此操作:

 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选项参数内。

希望有所帮助。

截至本文发表之日,我推荐使用jquery.mentionsInput插件。 它支持@mention标记,就像在facebook上一样,包含头像以及本地或ajax数据。

http://podio.github.com/jquery-mentions-input/

为了详细阐述Andrew Whittaker的答案,jQuery UI Autocomplete的source选项用于指定一个数组,其中包含触发小部件后要在下拉列表中显示的项目。 它可以定义为这样一个数组,一个返回这样一个数组的函数,或一个生成这种数组的资源的URL。

如果最终成为source值的数组为空,则窗口小部件将不会显示下拉列表。 因此,将source定义为只有在输入@ 时才能返回非空数组的函数,才能使窗口小部件按照您的意愿运行。

然而,小部件仅作为标签组件(此处称为提及 )管理实用程序的一部分,其具有3个组件:

  1. 自动填充模块 :在给定字符串的情况下,负责获取和显示可用于创建提及的项集的组件。

  2. 提及跟踪模块 :负责跟踪提及相关数据的组件; 在最小的位置,以及每个提及的表面和实质(如果存在)值应该在附加实用程序的输入元素的文本的所有修改中被跟踪。

  3. 提及视觉差异化模块 :负责区分提及文本与实用程序所附加的输入元素中其余文本的组件

用简单的英语进一步深入研究其余2个模块的实施将是乏味的; 看代码要好得多! 幸运的是,我已经提出了一个解决方案, Mentionator ,它是强大的(比这里建议的所有其他解决方案更多),结构良好,易于遵循,并且大量评论。 因此,值得一看的是,您是否只想要一个开箱即用的解决方案或参考材料来创建自己的解决方案。