禁用select2 clear下拉开启

Alb*_*rto 14 jquery clear jquery-select2

似乎select2 4默认打开清除当前所选项目时的下拉列表.以前版本的select2似乎没有那种行为,我正试图实现它,但现在没有运气.

有没有人知道如何挂钩清除事件所以我们可以禁用它的默认行为并清除所选的选项而不打开下拉列表?

干杯,Al

ada*_*amj 34

你不需要超时来完成这项工作,这是我的例子:

$('#my-select').select2({
    allowClear: true
}).on('select2:unselecting', function() {
    $(this).data('unselecting', true);
}).on('select2:opening', function(e) {
    if ($(this).data('unselecting')) {
        $(this).removeData('unselecting');
        e.preventDefault();
    }
});
Run Code Online (Sandbox Code Playgroud)


Sam*_*yan 11

可以确认,防止事件似乎由于某种原因不起作用,所以你可以在一些超时后关闭下拉列表:

$("select").select2({
    allowClear: true
}).on("select2:unselecting", function(e) {
    $(this).data('state', 'unselected');
}).on("select2:open", function(e) {
    if ($(this).data('state') === 'unselected') {
        $(this).removeData('state'); 

        var self = $(this);
        setTimeout(function() {
            self.select2('close');
        }, 1);
    }    
});
Run Code Online (Sandbox Code Playgroud)

这是一个工作小提琴:http://jsfiddle.net/obq3yLf2/