gpt4 book ai didi

javascript - 如何将对象字面量中的重复代码放入函数中并使用参数进行调用?

转载 作者:行者123 更新时间:2023-12-02 20:22:57 26 4
gpt4 key购买 nike

我将以下对象文字发送到 Ext JS Ext.FormPanel。

此表单有许多表单字段,例如“客户联系方式”、“联系原因”等

其中每一个都需要是下拉类型,而不是像现在这样简单的文本字段

我将第一个字段转换为下拉列表:

var form_customer_contact = new Ext.FormPanel({
frame:true,
labelWidth: 110,
labelAlign: 'right',
bodyStyle:'padding:0',
width: 300,
height: 600,
autoScroll: true,
itemCls: 'form_row',
defaultType: 'displayfield',
items: [{
fieldLabel: 'Customer Contact',
name: 'customerContact',
allowBlank:false,
value: 'Mr. Smith'
},{
fieldLabel: 'Reason for Contact',
width: 150,
xtype: 'combo',
mode: 'local',
value: '1',
triggerAction: 'all',
forceSelection: true,
editable: false,
fieldLabel: 'Produkt',
name: 'reason',
hiddenName: 'reason',
displayField: 'name',
valueField: 'value',
store: new Ext.data.JsonStore({
fields : ['name', 'value'],
data : [
{name : 'data correction', value: '1'},
{name : 'new contact', value: '2'},
{name : 'missing information', value: '3'}
]
})
}, {
fieldLabel: 'Communication',
name: 'communication',
value: 'test'
}, {
fieldLabel: 'Related Order',
name: 'relatedOrder',
value: 'test'
}, {
fieldLabel: 'Date/Time',
name: 'dateTime',
value: 'test'
}, {
fieldLabel: 'Notes',
name: 'notes',
value: 'test'
}
]
});

现在所有其他字段也需要转换为下拉列表,但由于大约80%的代码将保持相同,我想简单地调用函数,例如像这样:

getField('Reason for Contact', 'reason', {'data correction', 'new contact', 'missing information'})
getField('Communication', 'communication', {'telephone', 'fax', 'email'})

在 Javascript 中创建可以如上所述调用的函数或对象以减少本示例中的代码膨胀的最佳方法是什么?

最佳答案

您可以创建一个工厂函数来执行此操作,如下所示:

var createCombo = function(label, name, values) {
var i, data = [];

for(i = 0; i < values.length; i++) {
data.push({ name: values[i], value: i+1+'' });
}

return new Ext.form.ComboBox({
fieldLabel: label,
name: name,
width: 150,
mode: 'local',
value: '1',
triggerAction: 'all',
forceSelection: true,
editable: false,
displayField: 'name',
valueField: 'value',
store: new Ext.data.JsonStore({
fields : ['name', 'value'],
data : data
})
});
};

然后在您的项目列表中这样调用它:

createCombo('Reason for Contact', 'reason', ['data correction', 'new contact', 'missing information'])

关于javascript - 如何将对象字面量中的重复代码放入函数中并使用参数进行调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5301127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com