gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:33:28 24 4
gpt4 key购买 nike

我正在尝试动态清除 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").empty(); 

请注意,这将重置所有现有选择

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

关于javascript - 如何替换 Select2 选择框中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40896111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com