我有3个功能,所有设置点击事件触发相应的功能,在其各自的div。我想优化这个,所以我不会一遍又一遍地重复自己。写这个的最好方法是什么?最佳的方式来优化和合并这些jquery功能
//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);
}
})
});
这是产生以下错误“未捕获TypeError:无法读取属性'调用'未定义” –
我的错误!刚刚纠正。 – ykaragol
虽然我知道有很多方法可以做我想做的事情,但这似乎使它变得非常干净,并且不需要在我的视图中添加任何其他类型标记。谢谢! –