有大量选项可用于自动完成。它们中的大多数似乎都适用于输入的前几个字母。
在 Google Plus 中,输入 @
后,自动完成选项很快就会下降,无论它出现在表单字段中的哪个位置,并使用紧随 @
后面的字母进行引导自动完成。 (看起来也很不错!)
有人共享代码来执行此类操作吗?
有人可以尝试实现这个的玩具版本(例如在 jQuery 中)吗?
最佳答案
这可以通过 jQueryUI's autocomplete widget 实现。具体可以改编this demo以满足您的要求。这是一个例子:
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;
}
});
它正在工作:http://jsfiddle.net/UdUrk/
如果您需要更多信息(例如如何使其与远程数据源一起使用),请告诉我。
更新:以下是使用远程数据源(StackOverflow 的 API)的示例:http://jsfiddle.net/LHNky/ 。它还包括自动完成建议的自定义显示。
关于jquery - 在文本中间自动完成(如 Google Plus),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7089406/