【发布时间】:2016-04-24 15:20:13
【问题描述】:
我有 3 个函数都设置了点击事件,它们在各自的 div 中触发相同的函数。我想优化这一点,所以我不会一遍又一遍地重复自己。写这个的最好方法是什么?
//Progress Bar animation when tab clicked
$('#tab1').click(function () {
$('#stack .progress div').each(function () {
var display = $(this),
currentValue = parseInt(display.text()),
nextValue = $(this).attr('data-values'),
diff = nextValue - currentValue,
step = (0 < diff ? 1 : -1);
if (nextValue == '0') {
$(display).css('padding', '0');
} else {
$(display).css('color', '#fff').animate({
'width': nextValue + '%'
}, 'slow');
}
for (var i = 0; i < Math.abs(diff); ++i) {
setTimeout(function () {
currentValue += step
display.html(currentValue + '%');
}, 20 * i);
}
})
});
$('#tab2').click(function () {
$('#design .progress div').each(function () {
var display = $(this),
currentValue = parseInt(display.text()),
nextValue = $(this).attr('data-values'),
diff = nextValue - currentValue,
step = (0 < diff ? 1 : -1);
if (nextValue == '0') {
$(display).css('padding', '0');
} else {
$(display).css('color', '#fff').animate({
'width': nextValue + '%'
}, 'slow');
}
for (var i = 0; i < Math.abs(diff); ++i) {
setTimeout(function () {
currentValue += step
display.html(currentValue + '%');
}, 20 * i);
}
})
});
$('#tab3').click(function () {
$('#other .progress div').each(function () {
var display = $(this),
currentValue = parseInt(display.text()),
nextValue = $(this).attr('data-values'),
diff = nextValue - currentValue,
step = (0 < diff ? 1 : -1);
if (nextValue == '0') {
$(display).css('padding', '0');
} else {
$(display).css('color', '#fff').animate({
'width': nextValue + '%'
}, 'slow');
}
for (var i = 0; i < Math.abs(diff); ++i) {
setTimeout(function () {
currentValue += step
display.html(currentValue + '%');
}, 20 * i);
}
})
});
【问题讨论】:
标签: jquery performance dry