Select2事件用于创建新标签

har*_*ryg 14 javascript jquery jquery-select2

我正在使用jQuery Select2(v4)插件作为标签选择器.

我想监听在select元素中创建新标记的时间,并激活ajax请求以存储新标记.我发现有createTag事件,但每次在select2元素中输入一个字母时,这似乎都会触发.如我的小提琴所示:http://jsfiddle.net/3qkgagwk/1/

是否有类似的事件仅在新标签输入完毕后才会触发?也就是说它被一个封闭它的灰色盒子所包围.

Art*_*iak 30

遗憾的是我找不到任何原生方法.但如果你对简单的"解决方法"感兴趣,也许这会让你更接近:

$('.select2').select2({
    tags: true,
    tokenSeparators: [",", " "],
    createTag: function (tag) {
        return {
            id: tag.term,
            text: tag.term,
            // add indicator:
            isNew : true
        };
    }
}).on("select2:select", function(e) {
    if(e.params.data.isNew){
        // append the new option element prenamently:
        $(this).find('[value="'+e.params.data.id+'"]').replaceWith('<option selected value="'+e.params.data.id+'">'+e.params.data.text+'</option>');
        // store the new tag:
        $.ajax({
            // ... 
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

DEMO


[编辑]
(小更新:请参阅下面的@Alex评论)

只有在使用鼠标添加标记时,上述操作才有效.对于通过命中空格逗号添加的标签,请使用change事件.

然后你可以option使用data-select2-tag="true"属性(新添加的标签)进行过滤:

$('.select2').select2({
    tags: true,
    tokenSeparators: [",", " "]
}).on("change", function(e) {
    var isNew = $(this).find('[data-select2-tag="true"]');
    if(isNew.length && $.inArray(isNew.val(), $(this).val()) !== -1){
        isNew.replaceWith('<option selected value="'+isNew.val()+'">'+isNew.val()+'</option>');
        $.ajax({
            // ... store tag ...
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

演示2

  • 作者(select2)的答案似乎使用隐藏在文档中的不同方法来回答它:http://jsfiddle.net/3qkgagwk/2/ (2认同)