单击第一个建议时输入Typeahead

时间:2017-08-29 17:02:13

标签: javascript jquery typeahead.js twitter-typeahead

我的Typeahead.js设置目前用于鼠标点击建议,但不是Enter键。我正在尝试添加Javascript来处理它,但它没有表现。 tt-suggestion类是由typeahead动态生成的,当我检查Chrome中的代码时,我会看到它。我想要它做的是触发由typeahead.js生成的链接,而不是转到我没有或不想要的搜索页面。

JS:

    //handle Enter key
    $("#search-box").keypress(function(e){
        if(e.which == 13) {
            $(".tt-suggestion:first-child", this).trigger('click');
        }
    });

    //bloodhound
    jQuery(document).ready(function($) {
        jQuery(document).ready(function($) {
            // Set the Options for "Bloodhound" suggestion engine
            var engine = new Bloodhound({
                remote: {
                    url: '/search/file?q=%QUERY%',
                    wildcard: '%QUERY%'
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('q'),
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
            }, {
                displayKey: 'name',
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'filesList',

                // the key from the array we want to display (name,id,email,etc...)
                templates: {
                    empty: [
                        '<div class="list-group search-results-dropdown"><div class="text-muted">Nothing found.</div></div>'
                    ],
                    header: [
                        '<div class="list-group search-results-dropdown twitter-typeahead">'
                    ],
                    footer: [ '</div>'],
                    suggestion: function (data) {
                        return '<a href="/file/' + data.id + '/" class="list-group-item" style="background:#333;">' + data.name + '</a>'
                    }
                }

            });
        })});

HTML:

                <!-- SEARCH -->
                <li class="search">
                    <a href="javascript:;">
                        <i class="fa fa-search"></i>
                    </a>
                    <div class="search-box" id="search-box">
                        <form class="typeahead" role="search">
                            <div class="input-group">
                                <input type="search" name="q" placeholder="File Search" class="form-control search-input" autocomplete="off" />
                            </div>
                        </form>
                    </div>
                </li>
                <!-- /SEARCH -->

0 个答案:

没有答案