Select2.js v4.0: 如何使用本地数组数据源设置默认选择值?

Select2.js v4.0: how set the default selected value with a local array data source?

使用select2.js v4插件,当我使用本地数组数据作为源时,如何设置默认选择值?

例如使用此代码

var data_names = [{
  id: 0,
  text: "Henri",
}, {
  id: 1,
  text: "John",
}, {
  id: 2,
  text: "Victor",
}, {
  id: 3,
  text: "Marie",
}];

$('select').select2({
  data: data_names,
});

如何设置id 3为默认选择值?

$('.select').select2({
        data: data_names,
    }).select2("val",3);

这对我适用于 V4.0.3

$('.select').select2({
    data: data_names,
})
$('select').val(3);
$('select').trigger('change.select2');

最好为 select 发送另一个属性(selected 在我下面的例子中)并使用它来设置默认值。我做了类似下面的事情 -

var data_names = [{
  id: 0,
  text: "Henri",
}, {
  id: 1,
  text: "John",
}, {
  id: 2,
  text: "Victor",
}, {
  id: 3,
  text: "Marie",
  selected: true
}];

然后做

            $(".select").select2({
                data : data_names
            });
            data_names.forEach(function(name){
                if(name.selected) { 
                   $(".select").select2('val',name.id);
                }
            });

对我有用。

$('#select').select2({data: data_names}).val(3).trigger('change')