在默认情况下,select2 4在清除当前选定项时打开下拉列表。早期版本的select2似乎没有这种行为,我正在努力实现它,但目前没有运气。
是否有人知道如何连接到clear事件,这样我们就可以禁用它的默认行为,并在不打开下拉列表的情况下清除所选选项?
干杯,阿尔
发布于 2015-04-17 01:21:15
可以确认,由于某些原因,防止事件似乎不起作用,因此您可以在超时之后关闭下拉列表:
$("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);
    }    
});这是一个有用的小提琴:http://jsfiddle.net/obq3yLf2/
发布于 2016-03-04 22:38:38
您不需要超时才能完成此任务,下面是我的示例:
$('#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();
    }
});发布于 2017-03-23 14:30:29
在取消其中一个项目之后,我遇到了一个短期延迟的问题,这个解决方案为我解决了这个问题:
$(this).select2({
    multiple: 'multiple',
}).on("select2:unselecting", function(e) {
    var self = $(this);
    setTimeout(function() {
        self.select2('close');
    }, 0);
});https://stackoverflow.com/questions/29618382
复制相似问题