Disable dropdown opening on select2 clear
似乎select2 4在清除当前所选项目时默认打开下拉菜单。以前的select2版本似乎没有这种行为,我正在尝试实现它,但目前还没有运气。
有人知道如何挂接到clear事件,以便我们可以禁用它的默认行为并在不打开下拉菜单的情况下清除选定的选项吗?
干杯,
铝
您不需要超时即可执行此操作,这是我的示例:
1 2 3 4 5 6 7 8 9 10 | $('#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(); } }); |
可以确认,防止事件由于某种原因似乎不起作用,因此您可以在超时后关闭下拉菜单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $("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/
取消选择其中一项后,我遇到了短暂延迟的问题,此解决方案为我解决了该问题:
1 2 3 4 5 6 7 8 | $(this).select2({ multiple: 'multiple', }).on("select2:unselecting", function(e) { var self = $(this); setTimeout(function() { self.select2('close'); }, 0); }); |
另一个简单的实现:
1 2 3 4 5 6 7 8 9 10 | $('select').on('select2:unselect', function(evt) { $(this).select2({ placeholder : { id : '', text : '---None Selected---' }, allowClear : true, theme :"bootstrap" }).select2('close'); }); |