3

我的页面上有以下选择:

<select><option value="1" selected="selected">Caption</option></select>

我调用 select2 (v 4.0) init:

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name; },
    templateSelection: function(repo){ return repo.name; }
});

问题是 select2 正在重置默认选定值并显示空白字符串。有没有办法在 select2 init 上设置默认值?

4

2 回答 2

5

问题出在您的templateSelection方法中,因为您希望name数据对象上有一个属性。除了text现在需要并且如果重新映射它就不需要该方法的事实之外,您没有处理数据对象具有text属性的情况。

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name || repo.text; },
    templateSelection: function(repo){ return repo.name || repo.text; }
});

这应该可以解决您的问题并正确显示初始选择。

于 2015-05-20T15:12:01.470 回答
4

select2 文档现在有一个如何执行此操作的示例

// Set up the Select2 control
$('#mySelect2').select2({
  ajax: {
    url: '/api/students'
  }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
  type: 'GET',
  url: '/api/students/s/' + studentId
}).then(function (data) {
  // create the option and append to Select2
  var option = new Option(data.full_name, data.id, true, true);
  studentSelect.append(option).trigger('change');

  // manually trigger the `select2:select` event
  studentSelect.trigger({
    type: 'select2:select',
    params: {
      data: data
    }
  });
});

基本上,为 ajax 配置 select2,然后预填充所需的对象。魔术在最后一位完成,.trigger()这导致 select2 获取更改并呈现它。

于 2017-12-15T10:57:58.180 回答