我想在我的界面中添加一个组合框或菜单按钮,其中包含来自数组的数据。数组中的数据并不总是相同的,所以我需要按钮是"动态的"。我怎样才能做到这一点?如果数组发生变化,我无法指定模型...
编辑:我正在使用 ExtJS 6,所以我需要能够输入菜单参数:
menu: [{
text:'Menu Item 1'
},{
text:'Menu Item 2'
},{
text:'Menu Item 3'
}]
例:
1) 用户选择一个菜单项,然后单击发送按钮。
2)根据用户点击的项目的值,创建一个javascript数组,其中有时包含2个字段,有时包含10个字段。
3) 字段显示在新的菜单按钮或组合框中。
感谢您的帮助!
HTML
<input type="text" name="example" list="exampleList">
<datalist id="exampleList">
<option value="A">A</option>
<option value="B">B</option>
</datalist>
爪哇语
function generateOptionsFromDynamicArray (arr) {
// Get the datalist by id, cache option variable
var datalist = document.querySelector('#exampleList'),
option;
// Remove old options
while( datalist.firstChild ) {
datalist.removeChild(datalist.firstChild);
}
// Loop through array
for (var i = 0, l = arr.length; i < l; ++i) {
option = document.createElement('option');
option.setAttribute('value', arr[i]);
option.innerText = arr[i];
datalist.appendChild(option);
}
}
我创建了一个函数,您可以将该动态数组传递到该函数中以更新组合框,在本例中,我使用的是数据列表。关于这段代码的几点,你应该添加一个检查以确保arr是一个数组或"类似数组"(typedarrays我正在看你)。您还应该在发生这些更改时从 DOM 中删除数据列表,这样您就不会在每次迭代时重绘 DOM。
我创建了一个用于测试的小提琴。
您无法侦听数组change
事件,因此每当更改数组时,还必须调用以下函数:
function arrayToStore(array) {
var store = Ext.getCmp("myComboId").getStore();
//var store = Ext.getStore("myComboStore");
store.removeAll();
store.add(array.map(function(item) {
// This maps the array entry into a model you can add to the store.
// Instead of "field1", use your field name.
// If your array contains an object, you can preprocess it here.
// "field1" would be the default value if you have defined
// an implicit store by providing an array in the combo config:
// store:['item1','item2','item3'],
return {
field1:item
};
});
}