Select2 设置选中值新方法

Select2 set selected value new method

我使用如下代码为 select(使用 Select2)设置加载时的默认值:

$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).select2("val","<?php echo $garante; ?>");

在控制台上升级到版本 4.0 我读到:"Select2: The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead." 所以我尝试将我的代码更改为

$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).val("<?php echo $garante; ?>");

$('#soff_gar').select2({placeholder: "Scegli"}).val("<?php echo $garante; ?>");

但其中 none 有效。我究竟做错了什么?有什么提示吗?

来自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");

因此,如果您有一个 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>

在过去你会这样初始化它:

$("#mySelect").select2().select2("val","audi");

已替换为:

$("#mySelect").select2();
$("#mySelect").val("audi").trigger("change");

对你来说,我想这会转化为:

$('#soff_gar').select2({
  placeholder: "Scegli", 
  initSelection: true 
});
$('#soff_gar').val(<?php echo $garante; ?>).trigger("change");

尽管如此,您是否有任何理由以编程方式执行此操作?

参考我的例子,这也行得通:

<option value="audi" selected>Audi</option>

HTH