以下是我继承的文件的代码,其中包含许多手动重复代码:
toggleSizeField: function(action, element) {
var el = element.find('.size_custom').closest('.form-item');
this.toggle(action, el);
},
toggleHexField: function(action, element) {
var el = element.find('.color_custom').closest('.form-item');
this.toggle(action, el);
},
toggleCustomSize: function(val, element) {
if (val === 'custom_size') {
this.toggleSizeField('show', element);
return;
}
if (val === 'default') {
this.toggleSizeField('hide', element);
return;
} else {
this.toggleSizeField('hide', element);
}
},
toggleCustomHex: function(val, element) {
if (val === 'custom') {
this.toggleHexField('show', element);
return;
}
if (val === 'dark' || val === 'light') {
this.toggleHexField('hide', element);
return;
} else {
this.toggleHexField('hide', element);
}
},
$('fieldset.section').each(function() {
var $wrapper = $(this);
var $radios_1 = $wrapper.find('input.size:radio');
var $radios_2 = $wrapper.find('input.color:radio');
var initialVal_1 = $radios_1.filter(':checked').val();
var initialVal_2 = $radios_2.filter(':checked').val();
self.toggleCustomSize(initialVal_1, $wrapper);
self.toggleCustomHex(initialVal_2, $wrapper);
$radios_1.click(function() {
self.toggleCustomSize($(this).val(), $wrapper);
});
$radios_2.click(function() {
self.toggleCustomHex($(this).val(), $wrapper);
});
});
很抱歉,但它是我关注的重复代码。我该如何优化?我可以为这些方法创建循环吗?我不确定如何在循环中传递每个自定义方法/如何在each()
函数中调用它。