3

我正在尝试使用地名数据填充 select2 元素。我有一个定义的FormatSelection方法,但选择了一个项目时不会触发。

这是 HTML 元素:

<input id="location" size="30" type="text">​

Select2 与格式函数的绑定:

function locationFormatResult(location) {
    var markup = "<table class='location-result'><tr>";

    if (location.countryCode !== undefined) {
        markup += "<td class='flag-image'><img src='http://www.geonames.org/flags/x/" + location.countryCode.toLowerCase() + ".gif' /></td>";
    }

    markup += "<td class='location-info'>";
    markup += "<div class='location-name'>" + location.name + ", " + location.adminName1 + ", " + location.countryName + "</div>";
    markup += "</td></tr></table>";

    return markup;
}

function locationFormatSelection(location) {
    return location.name + ", " + location.adminName1 + ", " + location.countryName;
}

$(function () {
    $('#location').select2({
        placeholder: 'Location',
        allowClear: true,
        width: '260px',
        minimumInputLength: 2,
        ajax: {
            url: 'http://ws.geonames.org/searchJSON',
            dataType: 'jsonp',
            data: function (term) {
                return {
                    featureClass: 'P',
                    q: term
                };
            },
            results: function (data) {
                return {
                    results: data.geonames
                };
            }
        },
        formatResult: locationFormatResult,
        formatSelection: locationFormatSelection,
        dropdownCssClass: "bigdrop"
    });
});

你可以在这里看到完整的小提琴:http: //jsfiddle.net/6CVbw/1/

为什么选择一个项目不起作用?

4

1 回答 1

11

我想到了。当你在一个元素上实例化 select2 插件时,你必须指定一个 ID 属性。这有效:

$(function () {
    $('#location').select2({
        id: function(e) { return e.name + '|' + e.adminName1 + '|' + e.countryName },
        placeholder: 'Location',
        allowClear: true,
        width: '260px',
        minimumInputLength: 2,
        ajax: {
            url: 'http://ws.geonames.org/searchJSON',
            dataType: 'jsonp',
            data: function (term) {
                return {
                    featureClass: 'P',
                    q: term
                };
            },
            results: function (data) {
                return {
                    results: data.geonames
                };
            }
        },
        formatResult: locationFormatResult,
        formatSelection: locationFormatSelection,
        dropdownCssClass: "bigdrop"
    });
});

你可以在这里看到更新的小提琴:http: //jsfiddle.net/6CVbw/2/

于 2012-11-05T18:03:10.730 回答