使用 Bootstrap 的 Typeahead displayKey 函数返回值

9
我已经为Bootstrap的Typeahead定义了一个自定义建议模板,如下所示。但是,当我选择任何建议时,我只会在输入框中得到国家名称。因为我已经在displayKey参数中传递了国家。有没有办法可以像模板中那样选择国家城市名称一起出现在输入框中?
这里是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"
    }
]
1个回答

19

这个函数非常简单。只需要更新 display 参数,如下:

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

这里也更新了fiddle的代码: http://jsfiddle.net/geekowls/agrg3xhj/1/

干杯!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接