使用jquery以编程方式触发typeahead事件 [英] trigger the typeahead event programmatically using jquery

查看:437
本文介绍了使用jquery以编程方式触发typeahead事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用引导程序并正在处理typeaheads.我可以使用以下命令为输入字段预先设置类型:

I'm using bootstrap and working with typeaheads. I can set type aheads for an input field using:

var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];
$('#search-field').typeahead({source: subjects});

但这是静态的.我想提供自动建议功能,因此,当用户键入字符/单词时,我将提取用户键入的查询,并发出http请求以JSON格式提取建议.以下是我执行此操作的代码:

But this is static. I want to provide autosuggest feature and thus as user types a character/word, I fetch the query typed by user and make an http request to fetch the suggestion in JSON format. Following is my code to do this:

$('#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"事件处理程序:(!因此,有一种方法可以解决此问题,并在注册源后立即显示输入内容为此吗?

So as you can see, I fetch suggestions, create an array and set the source of typeahead. But the suggestions won't be shown because for that something has to be entered and doing that will again call my 'keyup' event handler :(! So is there a way to solve this issue and show the typeaheads as soon as source is registered for it??

推荐答案

所请求的功能已经内置在typeahead库中,它允许源成为

The requested feature is already built into the typeahead library, it allows the source to be a function as given the the documentation as given below

$('#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)
        });
    }
});

这篇关于使用jquery以编程方式触发typeahead事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆