我有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
雖然我知道有很多方法可以做我想做的事情,但這似乎使它變得非常乾淨,並且不需要在我的視圖中添加任何其他類型標記。謝謝! –