我必须编码以根据输入字段中输入的字符数从不同的端点获取typeahead的源。但是,只有在输入额外字符后才会显示来自新来源的建议。输入长度为3后应显示的建议在输入4个字符时显示
我在jsfiddle中创建了问题示例 http://jsfiddle.net/yj7hdzka/
来自标题为&#34的新数据源的示例新建议;此处有一些标题3"应该在我输入3个字符后立即显示,但在输入字段中输入4个字符后才会显示。
这是html和javascript
<input type="text" id="search-input">
<button id="switch">Switch Data Source</button>
<span id="sourceSelected"></span>
var data1 = [{
label: "some title here1",
desc: "some option here1",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}, {
label: "some title here2",
desc: "some option here2",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}];
var data2 = [{
label: "some title here3",
desc: "some option here3",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}, {
label: "some title here4",
desc: "some option here4",
category: [{
name: "category 1"
}, {
name: "categoy 2"
}]
}];
var titles = new Bloodhound({
datumTokenizer: function (data) {
return Bloodhound.tokenizers.whitespace(data.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data1
});
titles.initialize();
$('#search-input').typeahead({
highlight: true
}, {
name: 'titles',
displayKey: 'label',
source: titles.ttAdapter()
});
var sourceSelected = $('#sourceSelected');
var toggle = false;
$('#search-input').keyup(function(){
if($('#search-input').val().length > 2){
titles.local = data2;
sourceSelected.text('Data Source 2');
} else {
titles.local = data1;
sourceSelected.text('Data Source 1');
}
titles.initialize(true);
});
sourceSelected.text('Data Source 1');
答案 0 :(得分:0)
在尝试寻找解决方案时遇到了两个不同的问题:
我改变了什么:
var filter = function(suggestions) {
return $.grep(suggestions, function(suggestion) {
return -1;
});
}
var titles = new Bloodhound({
name: 'titles',
datumTokenizer: function(data) {
return Bloodhound.tokenizers.whitespace(data.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data1
});
titles.initialize();
$('#search-input').typeahead({
highlight: true
}, {
name: 'titles',
displayKey: 'label',
source: function(query, callbackFunc) {
titles.clear();
if ($('#search-input').val().length > 2) {
titles.local = data2;
sourceSelected.text('Data Source 2');
} else {
titles.local = data1;
sourceSelected.text('Data Source 1');
}
titles.initialize(true);
titles.get(query, function(suggestions) {
callbackFunc(filter(suggestions));
});
}
});
我的部分回答来自this SO answer,说实话,我并不完全知道如何实现typeahead插件的get()
方法以及为什么需要回调函数在我的解决方案中。
这是一个有效的jsfiddle,我希望这就是你要找的东西。