javascript - 使用 jquery 以编程方式触发 typeahead 事件

标签 javascript jquery twitter-bootstrap bootstrap-typeahead

我正在使用 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/

相关文章:

javascript - Yii- 客户端验证不适用于 CActiveForm

javascript - 存储 Bootstrap 数据 - 模态、徽章和警报

javascript - 使用 jQuery 显示和隐藏元素相关的 div

javascript - HTML5 音频未在 Android 2.3.6 上运行

javascript - 多个背景上的图像

javascript - 如何使用 HTML、CSS 和 postgres 构建简单的应用程序

javascript - 使用 JavaScript 验证复选框选中的属性是否不为空

javascript - JQuery/Javascript - 解决多个 promise

asp.net - iframe 的 onload 事件未在 firefox 中触发(与 ASP.NET 文件上传相关)

javascript - 动态显示列名