繁体   English   中英

无法在select2中选择通过jsonp填充的项目

[英]Unable to select items populated via jsonp in select2

我正在尝试使用geonames数据填充select2元素。 我定义了一个formatSelection方法,但是当选择一个项目时它不会触发。

这是HTML元素:

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

使用格式函数选择2绑定:

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/

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

我想到了。 在元素上实例化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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM