如何在没有触发事件的情况下更改 select2 的值?

How to change the value of select2 without trigger event?

我有一个 select2select 元素,我通过 jQuery

设置其值
$("#select2").val(elment_id).trigger('change');

但是,我已经定义了一个 onchange 事件处理程序。

$('#select2').on('change', function(e) {
//TODO
});

我只想更改(设置)select2 的值而不触发更改事件。有什么想法,怎么做?

有特殊活动刷新一下:

$("#select2").val(elment_id).trigger('change.select2');

来自文档:

It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. To limit the scope to only notify Select2 of the change, use the .select2 event namespace:

$('#mySelect2').val('US'); // Change the value or make some change to the internal state
$('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes

这取决于您想何时更改 select 元素中的值。这取决于其他因素?如果你想在 select 元素更改时触发事件,但不想触发已经定义的 'onchange' 操作,你可以给你的 select 下一个唯一的 class,然后构建该 class 的下一个 'onchange' 事件。但是,正如我之前所说,我不知道你想要实现什么,也很难说哪种解决方案是最好的

您可以像这样使用 Jquery 扩展创建新原型

$.fn.extend({
  Val: function(a) {
    $(this).val(a).trigger('change');
  }
})

$('#select2').Val(1)