【问题标题】:Can't get typeahead.js to work, no results will show无法让 typeahead.js 工作,不会显示任何结果
【发布时间】:2015-07-31 09:44:28
【问题描述】:

我已经尝试让 typeahead.js 工作 2 天了,但我拒绝相信它应该这么难。到目前为止,没有一个示例有效,我一直在努力找出问题所在。

首先,我的 typeahead.bundle.js 文件是从这个存储库下载的:

https://github.com/twitter/typeahead.js/tree/master/dist

我的代码如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Typeahead example</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
  </head>
  <body>

    <input id="search"/>

  <!-- jQuery -->
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  <!-- Latest compiled and minified Bootstrap -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <!-- Latest Typeahead.js -->
  <script src="typeahead.bundle.js"></script>

  <script type="text/javascript">
  var colors = ["red", "blue", "green", "yellow", "brown", "black"];

  $(document).ready(function() {

    $('#search').typeahead({source: colors});
  })

  </script>
  </body>
</html>

请帮我解决这个问题。

编辑:根据 sakir 的回答,我现在更改了我的 Javascript 代码以适应版本 10 的语法,但它仍然不会显示任何建议:

  <script type="text/javascript">
  var colors = ["red", "blue", "green", "yellow", "brown", "black"];

  $(document).ready(function() {

    $('#search').typeahead({
     highlight: true,
     hint: false
     }, colors);
  });

  </script>

【问题讨论】:

  • @sakir 没有错误,建议下拉菜单不会显示。

标签: javascript jquery typeahead.js typeahead twitter-typeahead


【解决方案1】:

我猜您的示例仅适用于 typeahead 0.9.x 版本。对于 10 版本,似乎有显着变化。您可以查看here了解更多信息。

我使用预输入版本 0.9 测试了您的示例,它工作正常。这是运行示例。

http://jsfiddle.net/179yevon/

如果您想使用最新版本的预输入,您可以查看示例here

从第一个示例中您可以看到,源参数接受类似source: substringMatcher(states) 的函数。 也许你可以根据那个改变你的代码

更新 有了 v.10,你可以做这样的事情。

  var colors = ["red", "blue", "green", "yellow", "brown", "black"];

var colorsource = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  // `states` is an array of state names defined in "The Basics"
  local: colors
});

$('#search').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'color',
  source: colorsource
});

这是提琴手

http://jsfiddle.net/qug5qdnp/

*血统所做的就是根据预输入源准备数据源。 如上所述,source 将函数作为参数和函数期望字符串 array.source 前面的类型只接受字符串数组,如果不打算使用血缘,则需要将其转换为数组数组

【讨论】:

  • 我尝试使用 10 版本的语法,但它仍然不起作用,我开始怀疑我的浏览器中是否发生了一些奇怪的事情。您介意在单个 HTML 页面中重新创建您的小提琴示例,以便我可以查看是否适合您,也适合我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2013-09-10
  • 1970-01-01
  • 2015-07-19
相关资源
最近更新 更多