为什么select2不设置所有数组元素?

时间:2018-11-14 15:21:24

标签: javascript jquery-select2

在这里,我有自定义代码,在其中测试将数组设置为select2值。但是,当我将数组项设置为select2时,尚未设置所有项。如何解决这个问题?

$('#tags').select2({
  multiple:true,
  tags: true,
  placeholder: 'Select tag...'
});

var tags = ["design", "template"];

$('#setTags').click(
  function(e) {
    $('#tags').select2('val', tags);
  }
);
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select name="tags[]" id="tags" multiple="multiple">
  <option value="design">Design</option>
  <option value="portfolio">Portfolio</option>
  <option value="template">Template</option>
</select>

<button id="setTags">Set tags</button>

1 个答案:

答案 0 :(得分:2)

您需要将$('#tags').select2('val', tags);替换为$('#tags').val(tags); 然后触发这样的更改事件。

$('#tags').select2({
  multiple:true,
  tags: true,
  placeholder: 'Select tag...'
});

var tags = ["design", "template"];

$('#setTags').click(
  function(e) {
    $('#tags').val(tags);
    $('#tags').trigger('change');
  }
);
#tags {
   width: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select name="tags[]" id="tags" multiple="multiple">
  <option value="design">Design</option>
  <option value="portfolio">Portfolio</option>
  <option value="template">Template</option>
</select>

<button id="setTags">Set tags</button>

Reference