typeahead.js中display配置项失效问题求助
问题:typeahead.js添加display配置后无结果显示
已经折腾这个问题好几个小时了,肯定是犯了某个低级错误,但实在毫无头绪……
已排查内容
文档
- typeahead.js jQuery用法文档
- Bloodhound配置选项文档
Stackoverflow相关问题
- typeahead.js使用远程数据时不显示下拉框
- typeahead.js/Bloodhound只显示一个结果
- typeahead.js显示所有预取数据
其他
示例/谷歌搜索等...
环境配置
使用MongoDB数据库,通过Mongoose/Node.js搭建搜索API,已验证API可正常工作。
HTML(Pug模板)
.answer-container form(method="POST" enctype="multipart/form-data")#answer-form.form label(for="new-answer") Answer: input(required minlength="1" maxlength="80" type="text" name="new-answer" id="new-answer" placeholder="Answer Text" autocomplete="off").new-answer-input br input(type="submit" name="submit" disabled autocomplete="off" value="Submit")#answer-submit-button .answer-messages
已验证Pug模板工作正常。
JS代码(typeahead + Bloodhound)
var answer_suggestions = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace("text"), queryTokenizer: Bloodhound.tokenizers.whitespace, remote:{ url: 'http://localhost:3000/api/v1/answers/search?text=%QUERY', wildcard: '%QUERY' } }); $('#new-answer').typeahead({ hint: true, highlight: true, autoselect: true, minLength: 2 }, { name: 'answers', source: answer_suggestions, display: 'text', limit: 10 });
核心问题
移除display配置项时,能正常看到API返回的结果;但添加该配置项后,下拉框完全没有结果显示。
API返回结果
[ { "_id": "64401c91bc76fdfca320c118", "text": "pneumothorax", "__v": 0 }, { "_id": "64403bb708645fb7abbe2db3", "text": "pneumothorax", "__v": 0 }, { "_id": "64403bdf08645fb7abbe2dbf", "text": "hemopneumothorax", "__v": 0 } ]
已尝试的方法
- 重构数据为JSON对象
- 在
display中使用函数(例如display: function(item) { return item.text; })
但以上方法都不起作用,现在只想让结果列表显示每条数据的text字段内容。
解决方法
问题出在Bloodhound数据源的适配和初始化环节,修改JS代码如下:
var answer_suggestions = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace("text"), queryTokenizer: Bloodhound.tokenizers.whitespace, remote:{ url: 'http://localhost:3000/api/v1/answers/search?text=%QUERY', wildcard: '%QUERY' } }); // 初始化Bloodhound实例 answer_suggestions.initialize(); $('#new-answer').typeahead({ hint: true, highlight: true, autoselect: true, minLength: 2 }, { name: 'answers', source: answer_suggestions.ttAdapter(), // 用ttAdapter转换为typeahead兼容的数据源 display: 'text', limit: 10 });
关键说明
- 必须初始化Bloodhound:旧版本typeahead.js需要手动调用
initialize()才能让Bloodhound正常工作,新版虽可能自动处理,但手动调用更稳妥。 - 用ttAdapter适配数据源:typeahead无法直接识别Bloodhound实例,必须通过
ttAdapter()转换格式——这是最容易忽略的点。你之前没加这个转换,移除display时typeahead用了默认的toString逻辑显示数据,添加display后就依赖正确的数据源适配,所以出现无结果的情况。
另外可以清除浏览器缓存再测试,确保没有缓存旧的错误代码。
内容的提问来源于stack exchange,提问作者Code2Empower
相关产品推荐
相关产品推荐

