2014-05-07 88 views
3

我想实现与我的网站上预输入功能的搜索和这里遵循的指示: http://twitter.github.io/typeahead.js/examples/#custom-templatesTypeahead.js与点击链接

然而,例子都显示预输入文本等等的onclick只是填充在文本框中。

对我来说,修改这个建议的最佳方式是实际链接到一个建议页面?例如。预输入返回3个对象:

  • 对象1:1的链接
  • 对象2:2链接
  • 对象3:3的链接

我应该怎么做才能有对象1..3返回,并点击它们需要用户链接1..3?

回答

8

写一个简单的例子,在http://jsfiddle.net/2RNFj/3/

你只需要提供的对象和它提供给Bloodhound设置的typehead来源:

var links = [{name: "abc", link: "http://www.example1.com"}, 
      {name: "nbc", link: "http://www.example2.com"}]; 

var source = new Bloodhound({ 
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    local: links 
}); 

source.initialize(); 

$('#custom-templates .typeahead').typeahead(null, { 
    name: 'matched-links', 
    displayKey: 'name', 
    source: source.ttAdapter(), 
    templates: { 
    empty: [ 
     '<div class="empty-message">', 
     'unable to find any Best Picture winners that match the current query', 
     '</div>' 
    ].join('\n'), 
     suggestion: Handlebars.compile('<p><a href="{{link}}">{{name}}</a></p>') 
    } 
}); 
+0

谢谢!这可以工作,但有一个警告,只有点击链接才能工作,如果用户通过键盘导航到链接并单击输入,则不起作用。这怎么能被支持? –

+1

我认为typeahead已经处理下拉项目的'Enter'按键事件。您可以添加事件处理程序来处理“Enter”事件以打开链接。 –

+0

需要下载并添加Handlebars I recon。 – Wrench