简体   繁体   中英

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? 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());
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM