使用 Ajax 源设置 select2 元素初始值的简单示例?

Simple example to set initial value of select2 element with Ajax source?

我正在尝试设置连接到 Ajax 数据源的 Select2 元素的初始值。

我正在使用 Select2 的 v4,并遵循 the docs,这说明 initSelection 已被替换。

我已经开始尝试适应 the example in the "Loading remote data" section of the Select2 documentation。这是我设置初始值的代码:

var $gitElement = $('.select2');
var option = new Option("yosssi/ejr", '29424443', true, true);
$gitElement.append(option);
$gitElement.trigger('change');

我最终得到一个显示 undefined (undefined) 的标签。我做错了什么?

JSFiddle 在这里:http://jsfiddle.net/t4Ltcm0f/4/

错误是您的 templateResulttemplateSelection 函数。 'repo' 参数是一个不包含 'name' 和 'full_name' 属性的对象,您应该使用 'text' 属性 代替。

function(repo) { 
    return repo.text || repo.name + ' (' + repo.full_name + ')';
}

在这里工作 JSFiddle:http://jsfiddle.net/45891w6v/1/