mar*_*arc 6 jquery-select2 jquery-select2-4 select2
我正在使用select2 v4.0.3和 JQuery。我将选择器初始化为:
$("#datatype").select2({
theme: "classic"
});
$("#unit").select2({
theme: "classic"
});
Run Code Online (Sandbox Code Playgroud)
然后我想检测一个变化#datatype并改变#unit我做的值如下:
$("#datatype").on('select2:select',function () {
$("#unit").val('21'); //udpate unit type to be 'none'
});
Run Code Online (Sandbox Code Playgroud)
问题是值 #unit设置为 21 但该选择器的显示标签没有更新。有什么建议 ?
似乎 select2 不知道该事件,或者尚未正确设置以侦听更改。我不确定解决方案是什么。我是网络技术的新手。
在挖掘 Select2 文档后,任何.val()更新都需要遵循 $('#unit').trigger('change');
所以在我的情况下,代码应该看起来像
$("#datatype").on('select2:select',function () {
$('#unit').val('21'); // Select the option with a value of '21'
$('#unit').trigger('change'); // Notify any JS components that the value changed
});
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于 select2 版本 4 及更高版本。
我还建议人们升级到版本 4,因为您可以直接调用更改值而无需指定 initSelect()
使用 select2 v4.0 您还可以触发change.select2事件来更新显示的标签。这可以防止正在侦听更改事件的其他组件引起副作用。
$("#datatype").on('select2:select',function () {
$('#unit').val('21'); // Select the option with a value of '21'
$('#unit').trigger('change.select2'); // Notify only Select2 of changes
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6982 次 |
| 最近记录: |