javascript 选择 select2 的 allowClear 选项时如何捕获事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28065551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:21:52  来源:igfitidea点击:

How to capture event when allowClear option of select2 is chosen?

javascriptjquery-select2jquery-events

提问by LA_

I've tried to capture select2:clearingevent

我试图捕捉select2:clearing事件

$("#my-select").on("select2:clearing", function (e) {
    console.log('cleared');
});

(jsfiddle)

( jsfiddle)

but it is not fired. I've also tried other versions (like select2:removedetc., see another questionwith similar problem), but it also doesn't work.

但它没有被解雇。我也尝试过其他版本(如select2:removed等,请参阅另一个有类似问题的问题),但它也不起作用。

I use select2 4.0.0-beta2.

我使用 select2 4.0.0-beta2。

回答by Mario A

The changelog of select2 4.0.0-beta2 states:

select2 4.0.0-beta2 的更新日志指出:

Removed events

select2-clearing - Use select2:unselecting instead

删除的事件

select2-clearing - Use select2:unselecting instead

https://github.com/select2/select2/releases

https://github.com/select2/select2/releases

回答by xhh

This works:

这有效:

$("#my-select").on("select2:unselecting", function(e) {

 });

回答by Kiry Meas

$("#my-select").on("select2:select select2:unselecting", function(e) {
   //do something here
 });

回答by Varan Sinayee

According to the select2 event documentations, all of the unselect, unselecting, clear and clearingevents will works !

根据 select2事件文档,所有取消选择、取消选择、清除和清除事件都将起作用!

But consider that usnselector unselectingevents should be used by single selectionmode, and clearor clearingshould be used by multi selectionmode. So the clear or clearing will fires if all of selected items cleared or clearing.

但考虑到usnselect取消选择事件应该由使用单一选择模式,并清除清除应使用多选择模式。因此,如果所有选定的项目都被清除或清除,清除或清除将被触发。

The differences between unselect and unselecting, is that unselecting fires before removing selection so you can prevented it.

取消选择和取消选择之间的区别在于取消选择会在删除选择之前触发,因此您可以阻止它。

Hope that it helps.

希望它有帮助。