如何替换Select2选择框中的选项

3
我正在尝试动态清除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">

我为你们做了这个调试


1
也许你需要添加 allowClear 选项、占位符和更改事件? - rad11
1个回答

4

Select2并没有提供一种在使用data选项添加选项之前完全清除选项的方法,因为这可以通过jQuery的.empty()函数来完成。

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

来自问题 #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?

You can clear out the existing options by calling .empty() on your original select.

$("select").empty(); 

Note that this will reset any existing selections

$("#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">


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接