3

我正在将 Typeahead.js 与 Bloodhound 建议引擎一起使用,并希望用户在搜索框中单击后立即显示该列表。

我发现这个 stackoverflow 问题(Twitter TypeAhead 以编程方式显示所有结果)与我相同,答案指向解决问题的 jsfiddle:http: //jsfiddle.net/5xxYq/

伟大的。

然而,它似乎只在不使用寻血猎犬作为预输入源时才有效。

例如,我分叉了他们的工作示例并将预输入源切换为使用 Bloodhound:http: //jsfiddle.net/5xxYq/31/。建议引擎工作正常(当我键入jo列表时出现),但是让建议出现在点击上的小技巧似乎不再起作用了。

关于如何使建议列表出现在用 Bloodhound 点击时的任何想法?

谢谢!

4

2 回答 2

3

如果您将此解决方案与 bloudhound 结合使用,则还需要更改 bloodhound.js 或 bundle.js。

在 typeahead.bundle.js 或 Bloodhound.js 添加找到此代码(第 450 行)

return matches ? _.map(unique(matches), function(id) {
                return that.datums[id];
            }) : [];

如果令牌输入为空,则添加此检查以返回所有建议:

if (tokens == '') return that.datums;

它现在看起来像:

if (tokens == '') return that.datums;
return matches ? _.map(unique(matches), function(id) {
                    return that.datums[id];
                }) : [];

我已经在您的小提琴中对此进行了测试,并且可以正常工作。

于 2014-11-26T09:22:08.113 回答
2

我认为可能有更好的方法来做到这一点。在不改变 Bloodhound/boundle js 的情况下,它仍然取决于可能会改变的内部 Bloodhound 实现。

var searchEngine = new Bloodhound({...});
function searchWithDefaults(q, sync) {
  if (q === '') {
    sync(searchEngine.index.all());
  } else {
    searchEngine.search(q, sync);
  }
}
$("#typeahead").typeahead({
  minLength : 0,
}, {
  name : 'typeahead',
  source : searchWithDefaults
});

此代码利用调用的 Bloodbound 内部搜索引擎的实现SearchIndex及其all()返回 Bloodhound 存储的数据的完整列表的函数。

答案灵感来自:

于 2015-12-22T13:05:42.353 回答