【问题标题】:Select2 show more valuesSelect2 显示更多值
【发布时间】:2017-04-13 05:05:47
【问题描述】:

我创建了 select2 下拉菜单。现在我想在这个下拉显示中按国家名称添加描述、城市、商店等。 如何添加国家城市名称、地区、商店等?

    (function($) {
        $(function() {
            var isoCountries = [
                { id: 'QA', text: 'Qatar',},
                { id: 'CA', text: 'Canada'},
                { id: 'CN', text: 'China'},
                { id: 'DE', text: 'Germany'},
                { id: 'RU', text: 'Russia'},
                { id: 'IT', text: 'Italy'}
            ];

            $("[name='market']").select2({
                placeholder: "Select a country",
                data: isoCountries
            });
        }); 
    })(jQuery);

【问题讨论】:

  • select2.github.io/examples.html#data-ajax使用该选项编辑select2的查看html:formatSelection: function(item) { return item.text + ' ' + item.xxx; // Some other property }
  • 查看示例页面源代码 (Ctrl+U) 以查看 select2 中的 html 中显示的额外数据

标签: jquery jquery-select2 select2


【解决方案1】:

检查下面的代码:

(function($) {
    var isoCountries = [
        { id: 'US', text: 'USA', description: 'New York'},
        { id: 'SP', text: 'Spain', description: 'Barcelona'}
    ];

    $("[name='market']").select2({
        placeholder: "Select a country",
        data: isoCountries,
        templateResult: function(data){
          return $('<span>')
            .html(data.text + ' - ')
            .append($('<i>')
            .html(data.description));
        },
        templateSelection: function(data){
          return $('<span>')
            .html(data.text + ' - ')
            .append($('<i>')
            .html(data.description));
        }
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>

<select name="market" style="width:100%;"></select>

它仅适用于 select2 版本 4+。 如果您想将它与以前的版本一起使用,而不是使用 templateResult 和 templateSelection,请使用 formatResult 和 formatSelection。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2017-03-02
    相关资源
    最近更新 更多