为什么我的typeahead在我用全称写源的时候能用,而在我把它和一个变量联系起来的时候却不能用?
它的工作原理是这样的。
var dt = [{"name": "Coop", "link": "post.php?d=1"},{"name": "Online", "link": "post.php?d=2"},{"name": "aaa", "link": "post.php?d=211"},{"name": "test jquery", "link": "post.php?d=220"}];
var source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: dt
});
source.initialize();
$('#custom-templates .typeahead').typeahead(null, {
displayKey: 'name',
source: source.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p><a href="{{link}}">{{name}}</a></p>')
}
});
但这个就不行了
var link = <?php echo json_encode($array);?>;
var source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: link
});
source.initialize();
$('#custom-templates .typeahead').typeahead(null, {
displayKey: 'name',
source: source.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p><a href="{{link}}">{{name}}</a></p>')
}
});
当我用 alert(link)
,我有相同的值。
的"... local
选项接受一个 阵列 或 javascript功能所以为了达到这个目的,你必须做这样的事情。
var source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: () => {
// here the program can search and handle the array
// then returns it
return array
}
});