如何替换 Select2 select 框中的选项

How to replace options in a Select2 select box

我正在尝试动态清除 Select2 选项列表,然后用新数据重新加载它。我读到的所有内容都告诉我,我可以像现在这样设置数据,但它只会附加数据,不会清除数据。

$("#optioner").select2();

$("#doit").click(function() {
  $("#optioner").select2({
    data: [{
      id: "real1",
      text: "Real 1"
    }, {
      id: "real2",
      text: "Real 2"
    }]
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>

<h1>Demo</h1>

<select id="optioner" class="select2">
  <option value="fake1">Fake 1</option>
  <option value="fake2">Fake 2</option>
</select>

<input id="doit" type="button" value="Real It Up">

fiddled that up赞成大家。

Select2 不提供在使用 data 选项添加选项之前完全清除选项的方法,因为它已经可以通过 jQuery .empty() 函数完成。

$("#optioner").empty()
    .select2({ data: /* ... */ });

来自 issue #3877:

This is the intended behavior of the data option. When Select2 is initialized with data, it converts the array of data objects into <option> elements that it can use.

So when you reinitialize it, it creates a second set of <option> elements.

If not, how do I re-populate the list of options / data for Select2?

您可以通过调用 .empty() 清除现有选项 原文select.

$("select").empty(); 

请注意,这将重置任何现有的 select离子

$("#optioner").select2();

$("#doit").click(function() {
  var $elem = $("#optioner");
  $elem.empty()
    .select2({
      data: [{
        id: "real1",
        text: "Real 1"
      }, {
        id: "real2",
        text: "Real 2"
      }]
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>

<h1>Demo</h1>

<select id="optioner" class="select2">
  <option value="fake1">Fake 1</option>
  <option value="fake2">Fake 2</option>
</select>

<input id="doit" type="button" value="Real It Up">