jQuery Select2 将数据附加到现有选择后初始化选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27561509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:25:37  来源:igfitidea点击:

Select2 Initialize select after appending data to existing select

jqueryjquery-select2

提问by Umes Bastola

In my select2 select, i need to append li after document is ready, and after appending, how can i reinitialize select2. If I once close and again open the select, the appended data are selectable but not as soon as i append. How can i reinitialize it.

在我的 select2 选择中,我需要在文档准备好后附加 li,附加后,我如何重新初始化 select2。如果我曾经关闭并再次打开选择,附加的数据是可选择的,但不是在我附加后立即选择。我该如何重新初始化它。

回答by Mivaweb

You have to destroy the select2 on these elements and then reinitialize it.

您必须销毁这些元素上的 select2,然后重新初始化它。

$("select").select2("destroy").select2();

回答by rusllonrails

Thanks to @Mivaweb for answer above ^

感谢@Mivaweb 以上答案^

So if I use:

所以如果我使用:

$("select").select2("destroy").select2();

then I'm getting following issue as some guys in comments on answer above:

然后我遇到了以下问题,因为有些人对上面的答案发表评论:

The select2('destroy') method was called on an element that is not using Select2

But it does not mean that it is not working, it works, but need to update approach a bit.

但这并不意味着它不起作用,它起作用,但需要稍微更新方法。

Working solution for me:

我的工作解决方案:

STEP1: destroy existing select2 instances

STEP1:销毁现有的 select2 实例

STEP2: update options or select

STEP2:更新选项或选择

STEP3: and now init new select2 instances

STEP3:现在初始化新的 select2 实例

For example:

例如:

$(".select2me-filter").select2("destroy");

... Here do option updates you need

$(".select2me-filter").select2();