【问题标题】:Typeahead.js / Bloodhound when clicking on suggestion, populates search box with object instead of nameTypeahead.js / Bloodhound 点击建议时,用对象而不是名称填充搜索框
【发布时间】:2017-04-03 19:58:17
【问题描述】:

当我开始使用 Typeahead.js 和 Bloodhound 在搜索框中输入高尔夫球场的名称时,下拉列表正确显示了高尔夫球场的名称。

问题

  • 当我单击包含球场名称的.tt-suggestion 时,填充搜索框的文本是高尔夫球场对象,而不是存储在var courses = [] 中的obj.name

scripts.js

<script type="text/javascript">
    var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
          var matches, substringRegex;

          // an array that will be populated with substring matches
          matches = [];

          // regex used to determine if a string contains the substring `q`
          substrRegex = new RegExp(q, 'i');

          // iterate through the pool of strings and for any string that
          // contains the substring `q`, add it to the `matches` array
          $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
              matches.push(str);
            }
          });

          cb(matches);
        };
    };

    var courses = [
        {% for content in COPY.courses%}
        { 
            "name": "{{content.name}}",
            "url": "/courses/{{content.slug}}",
        },
        {% endfor %}
    ];

    var source = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: courses
    });

    source.initialize();

    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'courses',
        source: source.ttAdapter(),
        templates: {
            empty: [
                '<div class="empty-message">We could not find any golf courses with that name</div>'
            ],
            suggestion: function(data) {
                return '<div><a href="' + course.url + '">' + course.name + '</a></div>';
            }
        }
    });
</script>

index.html

<div class="search search--home">
    <label class="search__label">Search all courses</label>
    <i class="fa fa-search" aria-hidden="true"></i>
    <input class="typeahead" type="search" name="" placeholder="Search all golf courses">
</div>

【问题讨论】:

    标签: javascript jquery input typeahead.js bloodhound


    【解决方案1】:

    如果您看到的是 JSON 对象而不是您想要的特定值,您可以使用 displayKey: 'name' 例如仅显示该值。

    解决方案来自这个StackOverflow question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多