我目前正在使用select2.js来创建一个组合框 . 数据源是ajax . 同时,我还将'allowClear'设置为true,用户可以“取消选择”当前选项 . 但我还希望它允许用户输入一个尚未填充的选项中的新值 . 为此,我让'tags'选项的值为true . 我还使用了'createTag'功能 .

但我意识到,一旦我这样做,'allowClear'功能就无法正常工作 . 我必须单击框右侧的“X”按钮两次才能取消选择一个值 . 其中我不明白为什么 .

以下是我的代码:

$('#company-code').select2({
        tags: true,
        ajax: {
            url: currentUrl + "working_url",
            data: function (params) {
                return {
                    q: params.term, // search term

                };
            },
            dataType: 'json',
            type: "GET",
            processResults: function (data) {
                return {
                    results: $.map(data, function (obj) {
                        return { id: obj.VNDCD, text: obj.VNDCD + "-" + obj.COMNM };
                    })
                };
            }


        },
        placeholder: "",
        selectOnClose: true,
        allowClear: true,
        minimumInputLength: 1,
        templateSelection: formatSelect2Selection,
        createTag: function (params) {
            var term = $.trim(params.term);

            if (term === '') {
                return null;
            }

            return {
                id: term,
                text: term + ' (new tag)'
            };
        }
    });