对于 Bootstrap 3,您可以使用Bootstrap-3-Typeahead。
您将不得不覆盖updater
andmatcher
函数。对于该matcher
函数,您可以使用替换函数中的代码,如下所示:
matcher: function (item) {
var last = this.query.split(',');
this.query = $.trim(last[last.length-1]);
if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
}
为您使用以下代码update
:
updater: function (item) {
return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
}
(匹配最后一次出现:JavaScript:替换字符串中最后一次出现的文本)
完整示例:
$('.typeahead').typeahead (
{
items: 4,
source: function (query, process) {
states = [];
map = {};
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
, updater: function (item) {
return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
}
, matcher: function (item) {
var last = this.query.split(',');
this.query = $.trim(last[last.length-1]);
if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
}
}
);