在 select2(版本 4.0.x)中,我找不到在运行时禁用选项的简单方法。
迄今为止最好的解决方案是调用 destroy
并重新创建 select2。即使这样可行,但我担心它会在我的生产环境中通过多个选择和大量选项对性能造成太大影响。作为奖励,由于绑定(bind)事件(不在 fiddle 中),我在重新创建操作期间从 select2 收到错误。
检查 fiddle :
https://jsfiddle.net/c3ubx018/
要触发问题,请一一打开所有选择。
然后单击切换按钮。
然后再次查看选择。
相关问题:How to disable options in select2
除了重新创建之外,我还尝试触发更改事件并向子树添加虚假选项,所有这些都有效但不会更新现有列表项。
最佳答案
如果您的数据不是很大,我认为这是一个很好的解决方案。
//create select2 data inside array
select2_data=[
{"id":1,"text":"A","disabled":false},
{"id":2,"text":"B","disabled":false},
{"id":3,"text":"C","disabled":false}
];
//initialize select2
$("#my_select2").select2({
data:select2_data
});
//After any event you can do this process
//For Now, We disabled the selected option and enable all other options
$("#my_select2").on('select2:select', function (e) {
//change data inside our array
for (let i = 0, il=select2_data.length; i < il; i++) {
id=$(this).val();//return selected option id
if(select2_data[i]["id"]==id){//disable selected item
select2_data[i]["disabled"]=true;
}else{//enable all other option in select2
select2_data[i]["disabled"]=false;
}
}
//now empty select2 and reinitialized it.
$('#my_select2').empty().select2({
data:select2_data
});
});
关于javascript - 如何在运行时禁用 select2 中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47755304/