jQuery Typeahead 自定义模板没有把手

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29223516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:34:35  来源:igfitidea点击:

Typeahead custom template Without Handlebars

jquerytypeahead.js

提问by Daniel Morris

I'm trying to implement the Typeahead.JS "Custom Template" example.

我正在尝试实现 Typeahead.JS “自定义模板”示例

$('#custom-templates .typeahead').typeahead(null, {
  name: 'best-pictures',
  displayKey: 'value',
  source: bestPictures.ttAdapter(),
  templates: {
    empty: [
      '<div class="empty-message">',
      'unable to find any Best Picture winners that match the current query',
      '</div>'
    ].join('\n'),
    suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
  }
});

Specifically this line:

特别是这一行:

suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')

Initially I didn't realise you need to explicitly require Handlebars as a dependancy:

最初我没有意识到您需要明确要求 Handlebars 作为依赖项:

Uncaught ReferenceError: Handlebars is not defined

When I remove Handlebars...

当我移除把手时...

suggestion: '<p><strong>' + value + '</strong> – ' + year + '</p>'

It gives another JS error:

它给出了另一个 JS 错误:

Uncaught ReferenceError: value is not defined

Is it possible to use a custom view template without using Handlebars engine?

是否可以在不使用 Handlebars 引擎的情况下使用自定义视图模板?

回答by Daniel Morris

Use this format:

使用这种格式:

suggestion: function(data) {
    return '<p><strong>' + data.value + '</strong> – ' + data.year + '</p>';
}

Taken from this thread.

取自这个线程

回答by Gaurav Sharma

This might help - I've integrated it with Bootstrap:

这可能会有所帮助 - 我已将其与 Bootstrap 集成:

<div class="col-lg-3" id="the-basics">
<input type="text" class="typeahead form-control" placeholder="my placeholder" aria-describedby="basic-addon1">
</div>

$('#the-basics .typeahead').typeahead(null, {
  name: 'best-pictures',
  display: 'imageUrl',
  source: function show(q, cb, cba) {
    console.log(q);
    var url = '/yoururl/'+q;
    $.ajax({ url: url })
    .done(function(res) {
      cba(res.list);;
    })
    .fail(function(err) {
      alert(err);
    });
  },
    limit:10,
  templates: {
    empty: [
      '<div class="empty-message">',
        'No data',
      '</div>'
    ].join('\n'),
    suggestion: function(data) {
      return '<p><strong>' + data.itemName + '</strong> - <img height:"50px" width:"50px" src='+data.imageUrl+'></p>';
    }
  }
});