我已经基于 https://www.algolia.com/doc/search/auto-complete 实现了自己的 Algolia PoC我现在正在为一个特定的用例而苦苦挣扎:如何处理不返回任何匹配项的搜索?
这是我的代码:
我已经能够识别和检测何时/何地没有返回命中,但除了使用 console.log() 之外我什么也做不了。我试图获得自定义 return_msg,但我无法调用该函数。 我还尝试在 suggestion: function(suggestion) 下进行一些调整,但如果没有返回任何匹配项,则永远不会调用此函数。 我也没有在 https://github.com/algolia/autocomplete.js 上找到关于此"template"部分的任何文档。
$('#q').autocomplete({ hint: false }, [
{
source: function(q, cb) {
index.search(q,
{ hitsPerPage: 10 },
function(error, content) {
if (error) {
cb([]);
return;
}
if (content.nbHits == 0)
{ return_msg = '<h5> Sorry, no result </h5>';
// DO something here
console.log(return_msg);
// console.log return "Sorry, no result"
}
cb(content.hits, content);
});
},
displayKey: 'game',
templates: {
suggestion: function(suggestion) {
return_msg = '<h5> '+ suggestion.MY_ATTRIBUTE + '</h5>'
return return_msg;
}
}
}
]).on('autocomplete:selected', function(event, suggestion, dataset) {
window.location = (suggestion.url);
});
任何指针将不胜感激 =)
最佳答案
使用数据集的 templates
选项,您可以指定在没有结果时使用的模板:
source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }),
templates: {
suggestion: // ...
header: // ...
footer: // ...
empty: function(options) {
return '<div>My empty message</div>';
}
}
完整文档 here .
关于javascript - 如果没有返回命中,则为 Algolia 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36144474/