我用這段代碼完整填充了我的場景。我修改了jquery站點的代碼,將重構事件重構爲。
auto_obj.change = function(event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function() {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// Trigger the event for value not found
$(select).trigger('autocompletenotfound', $(this).val());
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
input.data("autocomplete").term = "";
return false;
}
}
}
,並在源功能
auto_obj.source = function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var match = false;
response(select.children("option").map(function(i, value) {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text))) {
match = true;
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}
if (!match && i == select.children("option").size() -1 && self.options.allow_new) {
return {
label:'Create new <strong>'+ input.val() +'</strong>',
value: input.val(),
option: null
};
}
}));
};
這符合我的要求。希望對其他人有幫助。