select2动态更改项目 [英] select2 changing items dynamically
问题描述
我有两个链接的选择:第一个选择的每个值确定在第二个选择中将显示哪些项目。
I have two selects that are linked: Each value of the first select determines which items will be displayed in the second select.
第二个选择的值是存储在二维数组中:
The values of the second select are stored in a two-dimension array:
[ [{"id":1,"text":"a"}, {"id":2,"text":"b"},...],
[{"id":"1a","text":"aa"},{"id":"1b","text":"ba"},...],
...
]
第一个选择值确定用于填充第二个选择的索引。所以在第一个更改事件中我应该能够修改select-two包含的项目。
The first select value determines the index to be used to populate the second select. So in a 'change' event on the first I should be able to modify the items select-two contains.
阅读文档我认为我需要使用数据选项...但不是shure如何在初始化时加载数组数据,如果我在初始化后尝试执行相同操作,它似乎不起作用。
Reading documentation I think I need to use the "data" option... but not shure how as the example loads the array data on initialization and it seems to don't work if I try to do the same after initialization.
HTML
Attribute:
<select name="attribute" id="attribute">
<option value="0">Color</option>
<option value="1">Size</option>
</select>
Value:
<select name="value" id="value"></select>
<script>
var data = [ [{"id":1,"text":"black"}, {"id":2,"text":"blue"},...],
[{"id":"1","text":"9"},{"id":"1","text":"10"},...],
];
$('#attribute').select2().bind('change', function(){
// Here I need to change `#value` items.
$('#value').select2('data',data[$(this).val()]); // This does not work
);
$('#value').select2();
</script>
推荐答案
我为你做了一个例子来说明这是怎么回事可以这样做。
I've made an example for you showing how this could be done.
注意js,但我也将#value改为输入元素
Notice the js but also that I changed #value into an input element
<input id="value" type="hidden" style="width:300px"/>
我正在触发更改
事件获取初始值
and that I am triggering the change
event for getting the initial values
$('#attribute').select2().on('change', function() {
$('#value').select2({data:data[$(this).val()]});
}).trigger('change');
修改:
在select2的当前版本中,class属性从隐藏输入传输到select2创建的根元素,甚至是 select2-offscreen
类,它定位元素超出页面限制的方式。
In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen
class which positions the element way outside the page limits.
要解决此问题,只需添加 removeClass('select2-offscreen')
在同一元素上第二次应用select2之前。
To fix this problem all that's needed is to add removeClass('select2-offscreen')
before applying select2 a second time on the same element.
$('#attribute').select2().on('change', function() {
$('#value').removeClass('select2-offscreen').select2({data:data[$(this).val()]});
}).trigger('change');
我添加了一个新 代码示例 以解决此问题。
I've added a new Code Example to address this issue.
这篇关于select2动态更改项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!