jQuery Select2 设置选定值新方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28649240/
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
Select2 set selected value new method
提问by Lelio Faieta
I use to set the default value on load for a select (using Select2) with a code like this:
我使用这样的代码为选择(使用 Select2)设置加载时的默认值:
$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).select2("val","<?php echo $garante; ?>");
Upgrading to version 4.0 on console I read: "Select2: The select2("val")
method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead." So I tried to change my code to
在控制台上升级到 4.0 版,我读到:“Select2:该select2("val")
方法已被弃用,将在以后的 Select2 版本中删除。改用 $element.val()。” 所以我试图将我的代码更改为
$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).val("<?php echo $garante; ?>");
or
或者
$('#soff_gar').select2({placeholder: "Scegli"}).val("<?php echo $garante; ?>");
but none of them works. What am I doing wrong? Any hint?
但它们都不起作用。我究竟做错了什么?任何提示?
回答by James Hibbard
From the release notes:
从发行说明:
You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.
$("select").val("1"); // instead of $("select").select2("val", "1");
您应该直接在底层元素上调用 .val 。如果您需要第二个参数 (triggerChange),您还应该在元素上调用 .trigger("change")。
$("select").val("1"); // instead of $("select").select2("val", "1");
So, if you have a select element:
所以,如果你有一个 select 元素:
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
In the past you would have initialised it like so:
在过去,您会像这样初始化它:
$("#mySelect").select2().select2("val","audi");
$("#mySelect").select2().select2("val","audi");
This has been replaced with:
这已被替换为:
$("#mySelect").select2();
$("#mySelect").val("audi").trigger("change");
For you, I guess that would translate to:
对你来说,我想这会转化为:
$('#soff_gar').select2({
placeholder: "Scegli",
initSelection: true
});
$('#soff_gar').val(<?php echo $garante; ?>).trigger("change");
Although, is there any reason you're doing this programatically?
尽管如此,您是否有任何理由以编程方式执行此操作?
With reference to my example, this would also work:
参考我的例子,这也适用:
<option value="audi" selected>Audi</option>
HTH
HTH