ham*_*ama 0 javascript jquery refactoring case switch-statement
switch (options.effect) {
case 'h-blinds-fadein':
$('.child').each(function(i) {
$(this).stop().css({
opacity: 0
}).delay(100 * i).animate({
'opacity': 1
}, {
duration: options.speed,
complete: (i !== r * c - 1) ||
function() {
$(this).parent().replaceWith(prev);
options.cp.bind('click', {
effect: options.effect
}, options.ch);
}
});
});
break;
case 'h-blinds-fadein-reverse':
$('.child').each(function(i) {
$(this).stop().css({
opacity: 0
}).delay(100 * (r * c - i)).animate({
'opacity': 1
}, {
duration: options.speed,
complete: (i !== 0) ||
function() {
$(this).parent().replaceWith(prev);
options.cp.bind('click', {
effect: options.effect
}, options.ch);
}
});
});
break;
....more cases
}
Run Code Online (Sandbox Code Playgroud)
我有很多类似的其他案例.我能想到的一种方法是编写函数?我不确定我是否仍然对语言不熟悉
对不起,我是each()函数的索引,它是$('.child')的大小,而r和c只是包含'.child'的网格的'rows'和'columns'.r和c可以是任何数字,例如r = 5 c = 5
而不是使用开关,将案例特定数据存储在散列中.
然后运行主代码块并从散列中提取特定的任何效果类型.
function doit(e) {
var hash = {
'h-blinds-fadein': {
delay: function(i) { return i; },
complete: function(i) { return (i !== r * c - 1); }
},
'h-blinds-fadein-reverse': {
delay: function(i) { return (r * c - i); },
complete: function(i) { return i !== 0; }
}
}
$('.child').each(function(i) {
$(this).stop().css({
opacity: 0
}).delay(100 * hash[e].delay(i)).animate({
'opacity': 1
}, {
duration: options.speed,
complete: hash[e].complete(i) ||
function() {
$(this).parent().replaceWith(prev);
options.cp.bind('click', {
effect: options.effect
}, options.ch);
}
});
});
}
doit(options.effect);
Run Code Online (Sandbox Code Playgroud)