初始化后向Select2添加选项 [英] Add options to Select2 after inititialzation

查看:232
本文介绍了初始化后向Select2添加选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一件标准的事情,但是我一直在努力寻找一个清晰而简单的解决方案.

This seems like a standard thing to want to do, but I'm struggling to find a clear and simple solution.

我希望能够向已经初始化的Select2添加一个或多个其他选项.

I want to be able to add one or more additional options to an already initialized Select2.

我使用的是Select2的旧版本,但不确定该版本是什么版本.

I am using an older version of Select2, not sure what the version is off hand though.

推荐答案

您可以用与在标准<select>中解决问题相同的方式来解决大多数涉及Select2的问题.在这种情况下,相应的<select>问题将是:添加要使用javascript选择的选项.

You can solve most questions involving Select2 in the same way that they would be solved in a standard <select>. In this case, the corresponding <select> question would be: Adding options to select with javascript.

var option = new Option("text", "id");
$("select").append(option);

如果要在插入时选择它,只需在新选项上设置selected属性.

If you want it to be selected when it is inserted, you can just set the selected property on the new option.

var option = new Option("text", "id");
option.selected = true;

$("select").append(option);
$("select").trigger("change");

请注意,我还触发了change事件,以便Select2可以知道所选选项已更改.

Note that I also triggered the change event so that Select2 can know that the selected options have changed.

这篇关于初始化后向Select2添加选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆