0

我正在使用 select2 下拉控件来显示设施列表,例如设施 A、B、C...等。以及它的位置细节。我正在寻找以下输出,

在此处输入图像描述

目前我可以显示“设施名称”,但想从我的 json 对象中显示城市和州。 如何格式化我的结果以将它们显示为上述 html 格式? 到目前为止,这是我的代码。

<input type="hidden" id="ddlFacility" style="width:100%" />

$("#ddlFacility").select2({
        placeholder: "Select a Facility",
        ajax: {
            url: "my url",
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function ( term ) { return { term: term }; },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return { text: item.FacilityName, id: item.FacilityId }
                    })
                };
            }
        }
    });
4

2 回答 2

2

在您的 select2 选项中传递一个类似这样的函数并根据需要设置类的样式

...
placeholder: "Select a Facility",
    formatResult: function(item)
    { 
         return '<div class="facility">' + item.text + '</div><span class="city">' + item.city + '</span></div>';
    },
 ...

除了 id 和 text 之外,您可能需要 .map 函数来包含 Facilityname 和 City 值。

如果您希望所选值看起来相同,请对 formatSelection 选项使用相同的函数

于 2014-06-25T18:53:41.107 回答
0

请注意,现在如果使用 select2 版本 4 或更高版本,formatSelection并且formatResult被替换为templateSelectionandtemplateResult 官方文档的更多详细信息: https ://select2.org/upgrading/migrating-from-35

于 2022-02-08T17:09:44.487 回答