简体   繁体   English

使用选定的选项加载 Select2 而不触发更改?

[英]Loading Select2 with a selected option WITHOUT triggering change?

Is there any way to load select2 to a default value without triggering the change event?有没有办法在不触发更改事件的情况下将 select2 加载到默认值?

Currently, I am doing:目前,我正在做:

$('#mylist').val(2).trigger("change");

But this creates a delay where the user will at first see one option and then it will change, which is quite an annoyance.但这会造成延迟,用户首先会看到一个选项,然后它会改变,这很烦人。

I know I'm really late to answer this question.我知道我回答这个问题真的晚了。 I was facing the same issue.我面临着同样的问题。 But doing a bit of research I found a solution that works like a charm.但是做了一些研究,我发现了一个很有魅力的解决方案。

You can set an option using below code您可以使用以下代码设置选项

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

This solution will not trigger the main change event but sets the option to the select2 component.此解决方案不会触发主更改事件,而是将选项设置为select2组件。

Hope that helps you.希望能帮到你。

If you want to set a selected option, normaly you can do:如果要设置选定的选项,通常可以执行以下操作:

 $('#element').val('your_val').trigger('change');

But if you dont want to run the trigger, you must to destroy it first and then assign val before create again, like this:但是如果你不想运行触发器,你必须先销毁它,然后在再次创建之前分配val,像这样:

$('#element').select2('destroy');
$('#element').val('your_val').select2();

Set a default value in your HTML:在 HTML 中设置默认值:

<select id="myList">
   <option id="foo">option 1</option>
   <option id="bar" selected="selected">option 2</option>
</select>

Then call select2 on your element to initialize it:然后在你的元素上调用select2来初始化它:

$('#myList').select2();

or或者

$('#myList').select2("val", null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM