我正在使用 bootstrap 并使用 typeaheads。我可以使用以下方法为输入字段设置提前类型:
var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];
$('#search-field').typeahead({source: subjects});
但这是静态的。我想提供自动建议功能,因此当用户键入字符/单词时,我会获取用户键入的查询并发出 http 请求以获取 JSON 格式的建议。以下是我执行此操作的代码:
$('#search-field').on('keyup', function(){
// fetch the search query
var query = $(this).val();
// array containing suggestions
var suggestions=[];
$.getJSON('http://localhost:8983/solr/suggest/?q='+ query +'&wt=json&json.wrf=?', {
})
.done(function(response){
console.log(response);
$.each(response.spellcheck.suggestions[1].suggestion, function(){
// add the suggestions into the array
suggestions.push(this);
});
// set the source for typeahead
$('#search-field').typeahead({source: suggestions});
// how to trigger the search field to show these suggestions now???
});
正如您所看到的,我获取建议、创建一个数组并设置预输入源。但建议不会显示,因为为此必须输入一些内容,并且这样做将再次调用我的“keyup”事件处理程序:(!所以有没有办法解决这个问题并在注册源后立即显示输入提示为了它??
最佳答案
所请求的功能已内置到预输入库中,它允许源成为给定 documentation 的函数。如下所示
$('#search-field').typeahead({
source: function(query, process){
$.getJSON('http://localhost:8983/solr/suggest/?q='+ query +'&wt=json&json.wrf=?', {
}).done(function(response){
var suggestions=[];
$.each(response.spellcheck.suggestions[1].suggestion, function(){
// add the suggestions into the array
suggestions.push(this);
});
process(suggestions)
});
}
});
关于javascript - 使用 jquery 以编程方式触发 typeahead 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17521993/