问题描述
我想做到这一点,以便在搜索结果的自动完成链接中显示建议的结果,该链接指向网站上的特定餐厅.
I'd like to make it so the suggested results in my search's autocomplete link to the specific restaurant on the site.
注意:我碰到过此帖子,但是它使用了静态对象数组.与这篇文章不同,我希望从服务器端生成链接.
Note: I came across this post but it uses a static array of objects. Unlike this post I'm looking to generate links from the server-side.
var links = [{name: "abc", link: "http://www.example1.com"},
{name: "nbc", link: "http://www.example2.com"}];
var source = new Bloodhound({
...
local: links
});
在我的情况下,我正在从Rails查询数据库,因此name
将是餐厅的名称,而link
将是restaurant_path
.根据我当前的代码,我该如何完成?让我知道是否需要其他代码.
In my case I'm querying from Rails a database so the name
would be the restaurant's name and the link
would be the restaurant_path
. Based on what my current code, how I can I accomplish this? Let me know if any additional code is needed.
$(function() {
var restaurants = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/search/autocomplete?query=%QUERY",
wildcard: "%QUERY"
}
});
restaurants.initialize();
$('#autocomplete').typeahead(null, {
displayKey: 'name',
source: restaurants.ttAdapter()
});
});
我的餐厅路径当前的外观如下:
The way my restaurant path currently looks is as follows:
localhost:3000/restaurants/blue-smoke
更新:
根据guest271314的建议,我能够找到我的餐厅对象的返回值,其中包括适当的段(即blue-smoke
)以链接建议的结果.
Following guest271314 suggestion I was able to find the return value for my restaurant objects, which includes the appropriate slugs (i.e. blue-smoke
) to link up the suggested results.
推荐答案
尝试使用第二个.typeahead()
初始化对象的templates
和suggesstion
选项.请参见键入示例-自定义模板
Try using templates
, suggesstion
option of second .typeahead()
initialization object . See Typeahead examples - Custom Templates
$('#autocomplete').typeahead(null, {
displayKey: 'name',
source: restaurants.ttAdapter(),
templates:{
suggestion:function(data) {
return "<a href=" + data.slug + ">"+ data.name +"</a>"
}
}
});
这篇关于使用typeahead.js创建可点击的动态链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!