typeahead.js搜索框使用回车键导航

4
我将为您翻译以下内容:

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

这是我的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>')
    }       
});
});

当input类型为"text"时,如果我使用键盘导航并用enter键进行选择,它只会填充文本框。我希望按下enter键可以等同于点击行项目。我需要改变什么?

2个回答

4

我成功地将以下内容添加到我的JavaScript中,并且它很好地运行了

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

1
不要在项目中嵌入 href。而是在您的 typeahead 中使用以下 select 函数:
 select: function( event, key ) {
            window.location.href ="Your-Key-related-url-here";
        }

对我来说可以正常工作。如有任何进一步问题,请告知。


抱歉,我对JavaScript不太熟悉,不知道如何在我的代码中添加这行。Shailesh,你能具体说明一下我需要编辑哪段代码才能使它起作用吗?谢谢! - Ian Lin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接