清除Typeahead.JS查询时出现缺少源错误

Missing Source error when clearing Typeahead.JS query

本文关键字:错误 Typeahead JS 查询 清除      更新时间:2023-09-26

我试图在字段("#addtags")上使用Twitter的typeahead.js来建议添加标签,但当我选择某个内容时,该字段会在应该清除时保留我刚刚输入的值。

我尝试了这里提供的解决方案(设置typeahead的选定值),即使用$("#id").typeahead('setQuery', query);清除字段。然而,当我这样做时,我的控制台中出现了一个错误:Uncaught Error: missing source.

有办法绕过这个吗?清除字段的代码是底部上方的一行,其余部分为上下文提供。

//===========================
//Typeahead.js
//===========================
var tagApi = $("#addtags").tagsManager();
var addtags = new Bloodhound({
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d['tag']); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    dupChecker:true,
//  remote: '/tags/tags/search.json?q=%QUERY',
    prefetch: {url: '/tags/tags/search.json?q='}
});
addtags.initialize();
$('#addtags').typeahead({
    hint:true,
    highlight:true,
    autoselect:false,
    dupChecker:true,
    },
{
    displayKey: 'tag',
    source: addtags.ttAdapter(),
}).on('typeahead:selected', onTagSelect);
function onTagSelect($e, datum) {
    tagApi.tagsManager("pushTag", datum['tag']);
    //This is where I'm trying to clear the input:
    $('#addtags').typeahead('setQuery', ''); 
    };

我创建了一个jsfiddle来展示如何清除所选建议:

http://jsfiddle.net/Fresh/ecq0c0ph/

尝试搜索电影,然后选择一个建议;该建议将用于填充一些字段,然后将清除查询输入控件。

简言之,为了在选择建议时清除建议,请为Typeahead的所选事件创建一个事件处理程序,然后使用其API将值设置为空字符串,例如

.bind("typeahead:selected", function () {
    $('.typeahead').typeahead('val', '');
});