Javascript 选择2个标签:动态向输入添加标签

Javascript 选择2个标签:动态向输入添加标签,javascript,php,jquery,jquery-select2,Javascript,Php,Jquery,Jquery Select2,我正在寻找一个解决方案,将标签添加到输入标签字段 我知道可以预加载标记,但我没有找到向输入添加标记的方法。也就是说,使用特定的函数,我可以附加一个选择(带有ID和文本) 我已经找了不少了,但也许我陷入了死循环。有什么建议吗 我是这样初始化的: $('.select2Input').select2({ tags: { 0: { id: 'the id', text: 'the text'

我正在寻找一个解决方案,将标签添加到输入标签字段

我知道可以预加载标记,但我没有找到向输入添加标记的方法。也就是说,使用特定的函数,我可以附加一个选择(带有ID和文本)

我已经找了不少了,但也许我陷入了死循环。有什么建议吗

我是这样初始化的:

    $('.select2Input').select2({
        tags: {
            0: {
                id: 'the id',
                text: 'the text'
            }
        },
        multiple: true,
        minimumInputLength: 2
    });

正如我在这个相关问题中提到的,诀窍在于在需要更改初始化选项时销毁并重新创建select2。我怀疑在你的情况下,这也是你需要做的

基本语法是

$('#categoryid').select2("destroy");
createmycategoryidselect();

function createmycategoryidselect() {
   // standard options
   $opts = { ... }
   // gather the current set of tag values and stick them in this new instance.
   $opts.tags = { ... new tags ... }
}

分享你的代码开始…完成。但我非常怀疑它是否有助于解决我的问题。你可以怀疑,或者阅读以下内容: