我正在使用 algolia search对于我的 Rails 应用程序,我使用 typehead.js 设置了自动完成方法.但是当我在 URL 中有大写字母时我无法正确重定向...这是我的代码:
// replace YourIndexName by the name of the index you want to query.
var index = algolia.initIndex('Pin');
// Mustache templating by Hogan.js (http://mustache.github.io/)
var template = Hogan.compile('<div class="hit">' +
'<a href="http://yhumans.com/{{{twitter}}}">'
+
'<div class="small-text">' +
'{{{ _highlightResult.name.value }}} ' +
'</div>' +
'<div class="small-text">' +
'@' +
'{{{ _highlightResult.twitter.value }}} ' +
'</div>' +
'</a>' +
'</div>');
// typeahead.js initialization
$('#user-search').typeahead(null, {
source: index.ttAdapter({ hitsPerPage: 5 }),
displayKey: 'twitter',
templates: {
suggestion: function(hit) {
// select matching attributes only
hit.matchingAttributes = [];
for (var attribute in hit._highlightResult) {
if (attribute === 'name' || attribute == 'twitter') {
// already handled by the template
continue;
}
// all others attributes that are matching should be added in the matchingAttributes array
// so we can display them in the dropdown menu. Non-matching attributes are skipped.
if (hit._highlightResult[attribute].matchLevel !== 'none') {
hit.matchingAttributes.push({ attribute: attribute, value: hit._highlightResult[attribute].value });
}
}
// render the hit using Hogan.js
return template.render(hit);
}
}
});
问题出在我用来让用户点击结果访问页面的这一行:
<a href="http://yhumans.com/{{{twitter}}}">'
事实上,我的一些用户在他们的 Twitter 用户名中使用了大写字母,因此我无法在搜索结果中正确重定向到他们的个人资料。
让我解释一下:http://yhumans.com/myname是正确的网址。 http://yhumans.com/MyName是一个错误的网址 我尝试对该变量使用小写字母:“twitter”。但是我找不到正确的方法。
我知道一种方法是将 twitter 变量小写。但问题是函数“downcase!”似乎在 js 中不起作用。
有什么想法吗?
最佳答案
首先,两个不会直接回答问题但相关的评论:
- 使用 Hogan 模板,当文本中不应该包含 HTML 时,您应该使用
{{variable}}
,而当它包含 HTML 时,您应该使用{{{variable}}}
应该。这就是您应该使用{{twitter}}
的原因。 - Algolia 实际上已经将
typeahead.js@0.10
fork 到autocomplete.js
中,你应该看看那个。
话虽这么说,你给了一个解决方案,即使你是对的,.downcase!
不存在,它实际上是.toLowercase()
.
在您的建议功能中,只需将 twitter
属性小写即可:
function (hit) {
hit.twitter = hit.twitter.toLowerCase();
// ...
}
这种处理自动完成重定向的方式的一个问题是用户将无法使用他/她的键盘来选择结果。 autocomplete.js
和 typeahead.js
的推荐方法是分别使用 autocomplete:selected
或 typeahead:selected
事件:
$('#user-search').typeahead(/* ... */).on('typeahead:selected', function (ew, selection, dataset) {
// Redirect to http://yhumans.com/my-twitter-name
window.location.href = 'http://yhumans.com/' + selection.twitter;
});
要在用户悬停或使用箭头选择结果时向用户显示当前选择,您可以使用 .aa-hint
(autocomplete.js
) 或 .tt-hint
(typeahead.js
)。
关于javascript - Algolia 搜索 : access results onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009541/