Typeahead的工作原理是用全英文字母书写的源码,但当与一个变量相关联时就不行了。

问题描述 投票:0回答:1

为什么我的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),我有相同的值。

javascript typeahead.js typeahead bootstrap-typeahead bloodhound
1个回答
0
投票

的"... 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
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.