【问题标题】:typeahead.js search box navigation with enter keytypeahead.js 搜索框导航,带回车键
【发布时间】:2014-05-09 04:39:51
【问题描述】:

我正在尝试使用 typeahead.js 实现一个搜索框,用户可以通过单击 typeahead 中的行项目或使用键盘上下选择条目并通过 enter 键导航到它们来导航到条目。

这是我的html

<div id="remote">
  <input class="typeahead" type="text" placeholder="Search for people"> 
</div>

这是我的javascript

$(document).ready(function() {
var castDirectors = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: '../api/v1/search/people_typeahead',
  remote: '../api/v1/search/people_typeahead?q=%QUERY',
    dupDetector: function(remoteMatch, localMatch) {
        return remoteMatch.value === localMatch.value;
    }
});

castDirectors.initialize();

$('#remote .typeahead').typeahead(null, {
  name: 'cast-directors',
  displayKey: 'value',
  source: castDirectors.ttAdapter(),
    templates: {
        empty: [
      '<div class="empty-message">',
      'no matching names',
      '</div>'
    ].join('\n'),
        suggestion: Handlebars.compile('<p><a id="typeahead" href="{{link}}">{{value}}</a></p>')
    }       
});
});

使用输入类型=“文本”,如果我使用键盘导航并使用回车键选择,它只会填充文本框。我希望输入键等同于单击该行项目。我需要改变什么?

【问题讨论】:

    标签: javascript jquery typeahead.js


    【解决方案1】:

    设法将以下内容添加到我的 javascript 中,效果很好

    $('#remote .typeahead').on('typeahead:selected', function (e, datum) {
        window.location.href = datum.link
    });
    

    【讨论】:

      【解决方案2】:

      不要在您的项目中添加href。但是在你的 typeahead 中使用如下的 select 函数:

       select: function( event, key ) {
                  window.location.href ="Your-Key-related-url-here";
              }
      

      它对我有用。如果有任何进一步的问题,请告诉我。

      【讨论】:

      • 对不起,我对 javascript 有点陌生,不知道如何在我的代码中添加这一行。您能否更具体地说明我需要编辑哪些代码才能使其工作 Shailesh?谢谢!
      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多