初始函数如下所示:
function addressTypeaheadInitialize() {
$('.address').typeahead().on('keyup', function(ev) {
ev.stopPropagation();
ev.preventDefault();
if ($.inArray(ev.keyCode, [ 40, 38, 9, 13, 27 ]) != -1) {
return;
}
var self = $(this);
self.data('typeahead').source = [];
if (!self.data('active') && self.val().length > 0) {
self.data('active', true);
self.addClass('hint-loading');
$.ajax({
type : 'post',
url : '/jetty/typeahead_address',
data : {
query : this.value
}, /*
* ie {'TYPE':$ (this).attr('data-input-type'),
* 'VAR2','test2'}
*/
dataType : 'json',
cache : false,
success : function(data) {
self.data('active', true);
var source = [], highlights = [], i = data.source.length;
while (i--) {
source[i] = data.source[i];
highlights[i] = data.highlights[i];
}
self.data('typeahead').highlighter = function(item) {
var id = source.indexOf(item);
return highlights[id];
};
self.data('typeahead').source = source;
self.trigger('keyup');
self.data('active', false);
self.removeClass('hint-loading');
},
error : function(jqXHR, textStatus, errorThrown) {
self.removeClass('hint-loading');
}
});
self.data('active', false);
}
});
}
我尝试以这种方式使其适用于新的类型:
function addressTypeaheadInitialize() {
var suggestions = function(query, cb) {
$.ajax({
type : 'post',
url : '/jetty/typeahead_address',
data : {
query : query
},
dataType : 'json',
cache : false,
success : function(data) {
console.log(data);
var source = [], highlights = [], i = data.source.length;
while (i--) {
source[i] = data.source[i];
highlights[i] = data.highlights[i];
}
cb(source);
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
var options = {
highlighter : function(item) {
var id = source.indexOf(item)
return highlights[id];
},
source: suggestions,
}
$('.address').typeahead(null, options);
}
现在我甚至无法在表单中输入任何文字!我做错了什么?