javascript - 如何在不触发事件的情况下改变select2的值?

标签 javascript jquery jquery-select2

我有一个 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

关于javascript - 如何在不触发事件的情况下改变select2的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55897877/

相关文章:

angularjs - Select2 标记输入失去值 AngularJS

javascript - 根据其他输入字段从 json 选择2

javascript - 更改 Select2 以显示 'n of m items selected'

javascript - 为大型代码库编写适当的可维护可读 jQuery 的行业和社区最佳实践是什么?

javascript - 在动态位置生成下拉菜单

php - 将 div 转换为图像的最佳方法?使用 php、javascript 或 jquery

javascript - 通过字长而不是字符数运行脚本

javascript - 通过比较 2 个 JavaScript 数组生成表格数据

javascript - kendo ui Grid 虚拟滚动 - 滚动在哪里?

jquery - Twitter Typeahead.js Bloodhound 远程返回未定义