【问题标题】:trigger the typeahead event programmatically using jquery使用 jquery 以编程方式触发 typeahead 事件
【发布时间】:2013-07-08 08:23:11
【问题描述】:

我正在使用引导程序并使用预输入。我可以使用以下方法为输入字段设置类型提前:

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'事件处理程序:(!所以有没有办法解决这个问题并在源注册后立即显示预输入为了它??

【问题讨论】:

    标签: javascript jquery twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    请求的功能已经内置到 typeahead 库中,它允许源是一个函数,如下所示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)
            });
        }
    });
    

    【讨论】:

    • 如果您能向我提供此文档的链接,我将不胜感激,以便我可以探索更多选项。感谢您的帮助。
    • @stalin,这是一个传递给源函数的回调方法,必须用动态源数组调用
    • @stalin 我已经在答案中添加了指向文档的链接。您可以在选项部分下再次找到它here,阅读所有可用选项
    • @stalin 你可以删除 keyup 处理程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多