【问题标题】:Return values with Bootstrap's Typeahead displayKey Function使用 Bootstrap 的 Typeahead displayKey 函数返回值
【发布时间】:2015-10-16 00:16:15
【问题描述】:

我在 Bootstrap 的 Typeahead 中为建议定义了一个自定义模板,如下所述。但是,当我选择任何建议时,我只会在输入中得到 country 名称。由于我在 displayKey 参数中传递了 country。无论如何我可以在输入中选择 countrycity 名称(与模板中相同)?

这里是 JsFiddle:http://jsfiddle.net/geekowls/agrg3xhj/

我还阅读了 Typeahead 网站上的示例。但没有找到任何相关的东西。我只知道displayKey参数可以带一个函数。

$(document).ready(function () {

                        var dataSource = new Bloodhound({
                            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country', 'city'),
                            queryTokenizer: Bloodhound.tokenizers.whitespace,
                            identify: function (obj) { return obj.country; },
                            prefetch: "../Data/1.json"

                        });

                        function dataSourceS(q, sync) {
                                dataSource.search(q, sync);          
                        }

                        $('.typeahead').typeahead( {
                            minLength: 0,
                            highlight: true
                        }, {
                            name: 'countries',
                            displayKey: 'country',
                            source: dataSourceS,
                            templates: {
                                empty: [
                                    '<div class="empty">No Matches Found</div>'
                                ].join('\n'),
                                suggestion: function (data){
                                    return '<div>' + data.country + ' – ' + data.city + '</div>'
                                }
                            }
                        }
                        );
});

这是 Json 文件。

[
    {
    "country": "Holland",
    "city": "Amsterdam"
    },
    {
    "country": "Belgium",
    "city": "Brussel"
    },
    {
    "country": "Germany",
    "city": "Berlin"
    },
    {
    "country": "France",
    "city": "Paris"
    }
]

【问题讨论】:

    标签: javascript jquery typeahead.js typeahead bloodhound


    【解决方案1】:

    函数很简单。只需要将 display 参数更新为:

    display: function(item){ return item.country+'–'+item.city}
    

    还在这里更新了小提琴上的代码: http://jsfiddle.net/geekowls/agrg3xhj/1/

    干杯!

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多