我使用twitter typeahead和Bloodhound建议引擎,一切正常。以下是我的代码段
// instantiate the bloodhound suggestion engine
var searchData = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '<?php echo 'http://localhost/project1/perform/find?q=%QUERY'; ?>',
filter: function (data) {
return $.map(data.results, function (record) {
return {
title: record.title,
pageURL: record.pageURL
};
});
}
}
});
// initialize the bloodhound suggestion engine
searchData.initialize();
searchData.clearRemoteCache();
// instantiate the typeahead UI
$('#find').typeahead({
hint:false,
highlight: true,
minLength: 3
}, {
name:'search-data',
displayKey: 'title',
source: searchData.ttAdapter(),
templates: {
empty:[
'<strong>No Results Found.</strong>'
],
suggestion: Handlebars.compile('<p>{{title}}</p>')
}
}).on('typeahead:selected', function (e, suggestion) {
setTimeout(function(){document.location = suggestion.pageURL;}, 500);
}).on('typeahead:closed', function (e){
$loadingImg.hide();
});
我想做一些操作,比如显示发布按钮等,当远程服务器返回零结果时,我该如何捕获此事件?
答案 0 :(得分:1)
我不知道以下方法是否正确(如果错误则纠正我)
filter: function (data) {
if(data.results.length){
console.log('results found'); //do something
}else{
console.log('results not found'); //do something
}
return $.map(data.results, function (record) {
return {
title: record.title,
pageURL: record.pageURL
};
});
}
答案 1 :(得分:0)
我使用了typeahead notFound &#39;模板&#39;选项,从那里我可以设置一个链接按钮,对我来说在我的情况下更容易访问/可用。预先输入设置:
$('#remote .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2
},
{
name: 'sn-tags',
display: 'tag',
source: oBusqTags, //Bloodhound object
templates: {
notFound: '<p>No matches<br><a id="btnAddNewTag" href="#">Add New Tag</a></p>'
}
}).bind("typeahead:select", function(obj, datum, name) {
//add selection as an option on a select element
$('#lbxAddTag').append($('<option>', {
value: datum.id,
text: datum.tag
}));
});
这是该链接的监听者:
$('#remote').on('click', '#btnAddNewTag', function(e){
$('#lbxAddTag').append($('<option>', {
value: "0",
// this is tricky, as there aren't any matches then
// $('#remote .typeahead').typeahead('val') contains '',
// so i had to set an id for the typeahead input text box and
// 'manually' get its value
text: $('#tbxBusqTag').val()
}));
// as the text is already added as a select option
// i clean the typeahead input box
$('#remote .typeahead').typeahead('val','');
e.preventDefault();
});