【问题标题】:Why are the typeahead suggestions undefined?为什么未定义预先输入的建议?
【发布时间】:2014-02-08 17:21:50
【问题描述】:

希望这不是重复:Why does bloodhound.get() return undefined?

我升级到 typeahead.js 版本 0.10.0。以前的版本正确地返回了建议。现在我收到了undefined 的返回,代码如下:

// instantiate the bloodhound suggestion engine
var engine = new Bloodhound({
    datumTokenizer: function (d) { return [d]; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: ["(A)labama", "Alaska", "Arizona", "Arkansas"]
});

// initialize the bloodhound suggestion engine
engine.initialize();

$('#typeahead').typeahead(null, {
        source: engine.ttAdapter()
    });

这是我的小提琴:http://jsfiddle.net/ucUcn/6/

任何想法为什么会发生这种情况?

【问题讨论】:

    标签: typeahead typeahead.js bloodhound


    【解决方案1】:

    local 数组必须包含对象,而不是字符串本身。

    // instantiate the bloodhound suggestion engine
    var engine = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('d'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: [{
        d: "(A)labama"
      }, {
        d: "Alaska"
      }, {
        d: "Arizona"
      }, {
        d: "Arkansas"
      }]
    });
    
    // initialize the bloodhound suggestion engine
    engine.initialize();
    
    $('#typeahead').typeahead(null, {
      displayKey: 'd',
      source: engine.ttAdapter()
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
    <input id="typeahead" />

    解决上述问题:

    JsFiddle

    【讨论】:

    • 当你输入 A 时效果很好,但如果你输入 Ar 它就会消失
    • 看来我的 typeahead 链接指向最新版本,并且发生了重大更改。将保留更新版本的链接,因为在理想情况下,您将使用更新版本。
    【解决方案2】:

    正如@Chad 所说,结果数组必须包含对象。

    我只想补充一点,用于显示建议的默认值是value

    所以你可以做类似的事情

    var suggestionEngine = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "myUrl",
            filter: function (suggestions) {
                var mappedResult = $.map(suggestions[1], function(suggestion) {
                    return { value : suggestion }
                });
    
                return mappedResult;
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多