[英]Can the following code be shortened into a “ForLoop”?
Is it possible to shorten the following code into a "for loop" or anything of the sort? 是否可以将以下代码简化为“ for循环”或类似的形式? Any help would be greatly appreciated.
任何帮助将不胜感激。
$('#submit').click(function(){
var barOneValue = $('.barOne-value').val();
var barTwoValue = $('.barTwo-value').val();
var barThreeValue = $('.barThree-value').val();
var barFourValue = $('.barFour-value').val();
var barFiveValue = $('.barFive-value').val();
$('.barOne').attr('percentValue', barOneValue);
$('.barTwo').attr('percentValue', barTwoValue);
$('.barThree').attr('percentValue', barThreeValue);
$('.barFour').attr('percentValue', barFourValue);
$('.barFive').attr('percentValue', barFiveValue);
});
Something like : 就像是 :
['One', 'Two', 'Three', 'Four', 'Five'].forEach(function(item) {
$('.bar' + item).attr('percentValue', $('.bar'+ item +'-value').val());
});
As I mentioned in the comments, you can make a function to help: 正如我在评论中提到的,您可以创建一个函数来帮助您:
function int2Word(i){
var map = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
return map[i];
}
Then make your loop: 然后进行循环:
$('#submit').click(function(){
for(var i = 1; i < 6; i++){
$('.bar' + int2Word(i)).attr('percentValue', $('.bar' + int2Word(i) + '-value').val());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.