typeahead.js onselect item 重定向到新窗口

Me7*_*888 6 jquery typeahead bootstrap-typeahead typeahead.js

我使用远程 url 和 json 响应(新 typeahead.js)

我的 JavaScript :

$(document).ready(function() { 
$('input.country').typeahead({
valueKey: 'name',
remote : {
url : 'example.in/d.php?query=%QUERY',
filter: function (parsedResponse) {
  var dataset = [];   
for (i = 0; i < parsedResponse.length; i++) {
              dataset.push({
                name: parsedResponse[i].name
              });
            }
if (parsedResponse.length == 0) {
              dataset.push({
                name: "No results" 
              }); }
            return dataset;
        },
},
});;
})
Run Code Online (Sandbox Code Playgroud)

我的 json 响应:

[{"name":"诺基亚 110",url:"example.com/nokia-110"},{"name":"诺基亚 210",url:"example.com/nokia-210"}]

那么如何在所选名称上提供 URL 链接?

Jos*_*ter 5

Event Listener

$('input.country').on( 'typeahead:selected', function(event, selected_object, dataset) {
   window.location.href = selected_object.url
});
Run Code Online (Sandbox Code Playgroud)

This assumes that your selected_object has an attribute called url that contains a valid URL to redirect your browser to. There are variations as to the best way to set and get this url attribute and value but you can figure it out from here.


Tob*_*oby 2

您需要更新 Typeahead.js 使用的模板,并在其中显示 URL。

请参阅: https: //github.com/twitter/typeahead.js/#datum

对于与 Typeahead.js 配合良好的模板系统,我建议您查看http://twitter.github.io/hogan.js/