typeahead.js - Uncaught TypeError: this.displayText(...).toLowerCase is not a function

typeahead.js - Uncaught TypeError: this.displayText(...).toLowerCase is not a function

我一直在摆弄 typeahead.js 模板。无论我做什么,我都会收到以下错误:

Uncaught TypeError: this.displayText(...).toLowerCase is not a function in typeahead.min.js:2

我的 JavaScript 如下所示:

$('#search-field').typeahead({
    display: 'value',
    templates: {
        suggestion: function(data) {
            return '<p><strong>' + data.value + '</strong> – ' + data.titleid + '</p>';
        }
    },
    source: function (query, process) {
        return $.get(root + '/api/search.php', { query: query }, function (data) {
            console.log('data:' + data); //outputs the JSON correctly.
            data = $.parseJSON(data);
            return process(data);
        });
    }
});

其中 /api/search.php 看起来像:

[{"value":"Name1","titleid":"Test1"},{"value":"Name2","titleid":"Test2"},{"value":"Name3","titleid":"Test3"}]

我试过将其他示例中的代码直接复制到我的示例中,有时甚至是整个片段,但这也没有解决问题,尽管它在示例中确实有效。

我该如何解决这个问题,并让模板正常工作?

您可以在 GitHub 上查看 this issue and this issue。看来您在 source 中的对象必须有一个 name 属性,或者您必须自己定义一个 displayText 函数。链接的第二个问题有一个回复:

The document should make clear that: "You can add all the properties you wish on your objects, as long as you provide a "name" attribute OR you provide your own displayText method."

解决方案是在 typeahead 选项中添加 displayText 函数,如下所示:

$('#search-field').typeahead({
    ...
    displayText: function (item) { return item.value; }
    ...
});

其中 item.value 可以是您希望显示的任何 属性。

问题已解决。将 typeahead.js 包用于以下代码中使用的其他插件。

var search = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/api/search.php?query=%QUERY',
        wildcard: '%QUERY'
    }
});

$('#search-field').typeahead(null, {
    display: 'titleid',
    source: search,
    templates: {
        empty: [
            '<div class="empty-message">',
            'no results found.',
            '</div>'
        ].join('\n'),
        suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – {{titleid}}</div>')
    }
});

我从中学到了什么? typeahead.js 是一个很难使用的插件。