您可以通过为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
希望有帮助。