jQuery 清除 select2 而不触发更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17819709/
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-08-26 20:01:09  来源:igfitidea点击:

Clear select2 without triggering change event

jqueryjquery-select2

提问by Ryan Gill

I have a select2 input that I'm using and on 'change' I'm grabbing the values and performing an action. I'm trying to clear that select2 without triggering a change event. Is this possible?

我有一个我正在使用的 select2 输入,并且在“更改”时我正在获取值并执行操作。我试图在不触发更改事件的情况下清除该 select2。这可能吗?

To clear the select2 I'm using the following code:

要清除 select2 我使用以下代码:

$docInput.select2('data', null);

This clears the input as desired, but also triggers a change event which runs through my other code. There must be a way to silence the trigger. Any ideas?

这会根据需要清除输入,但也会触发通过我的其他代码运行的更改事件。必须有一种方法可以使触发器静音。有任何想法吗?

采纳答案by Mike Fielden

I believe all you need is:

我相信您只需要:

$docInput.select2('data', null, false);

$docInput.select2('data', null, false);

回答by Oleksii Polivanyi

You can use the following with Select2 4.x

您可以在 Select2 4.x 中使用以下内容

$docInput.val(null).trigger('change.select2');