jquery select2 v4 将新选项存储到数据

jquery select2 v4 store new options to data

我正在使用 Select2,我可以使用 tags: true 创建动态选项,但是当我 select 以前的选项时,新添加的选项消失了。

如何将其保存到数据中以使其始终可见?

我添加了一个 jsfiddle,但它不是很漂亮,但确实证明了我的问题

var data = [{
    id: 0,
    text: '<div style="font-size: 1.2em; color:green">enhancement</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
    title: 'enchancement'
},
{
    id: 1,
    text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>',
    title: 'bug'
}];

$("#other").select2({
    tags: true,
    data: data,
    escapeMarkup: function(markup) {
        return markup;
    },
    createTag: function(params) {
        var obj = {
            id: 'new_' + params.term,
            text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
            title: params.term
        };
        return obj;
    },
    insertTag: function (data, tag) {
        // Insert the tag at the end of the results
        data.push(tag);
    }
});

您需要触发select2:select功能

试试这个

$("#other").select2({
    tags: true,
    data: data,
    escapeMarkup: function(markup) {
        return markup;
    },
    createTag: function(params) {
        var obj = {
            id: 'new_' + params.term,
            text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
            title: params.term,
            isNew : true
        };
        return obj;
    }
}).on('select2:select', function (e) {
    if(e.params.data.isNew) {
        data.push({id: e.params.data.id, text: '<div style="font-size: 1.2em; color:blue">' + e.params.data.text + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>', title: e.params.data.text});
    }
});