问题描述
有吨选择那里做自动完成。大多数人似乎对正在输入前几个字母的工作。
There are tons of options out there for doing autocompletion. Most of them seem to work on the first few letters that are typed.
在谷歌加,自动完成选项不久键入后滴下来 @
,不管它发生在表单字段,并使用字母紧接着 @
来指导自动完成。 (这也看起来相当不错!)
In Google Plus, an autocomplete option drops down soon after typing @
, no matter where it occurs in the form field, and uses the letters immediately following @
to guide the autocomplete. (It also looks quite nice!)
有没有人共享code做这样的事情?
Has anybody shared code to do this sort of thing?
没有任何人有任何指针试图实现这种玩具的版本(例如jQuery中)?
Does anybody have any pointers for trying to implement a toy version of this (e.g. in jQuery)?
推荐答案
这是可能的。具体来说,可以适应,以满足您的要求。这里有一个例子:
This is possible with jQueryUI's autocomplete widget. Specifically, you can adapt this demo to satisfy your requirement. Here's an example:
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;
}
});
在这里,这是工作:
让我知道如果你需要任何更多的信息(比如如何使它与远程数据源工作)。
Let me know if you need any more information (such as how to make it work with a remote datasource).
更新:下面是使用远程数据源(计算器的API)的例子:。它还包括自动完成建议自定义显示。
Update: Here's an example using a remote datasource (StackOverflow's API): http://jsfiddle.net/LHNky/. It also includes custom display of autocomplete suggestions.
这篇关于自动完成文本的中间(如谷歌加)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!