-1

Possible Duplicate:
Any way to simplify this code?

What is the best way to simplify this for going from 1-19?

var backer1 = document.getElementById("backer-prediction-1").value;
var incentive1 = document.getElementById("incentive-cost-1").value;
var totalIncentive1 = parseInt(backer1,10) * parseInt(incentive1,10);

document.getElementById("incentive-total-1").value = totalIncentive1;

var backer2 = document.getElementById("backer-prediction-2").value;
var incentive2 = document.getElementById("incentive-cost-2").value;
var totalIncentive2 = parseInt(backer2,10) * parseInt(incentive2,10);

document.getElementById("incentive-total-2").value = totalIncentive2;

Last one I posted they gave me a "for" loop.

Still learning this stuff.. Very New, THANKS!!!

4

4 回答 4

3

Use Array in javascript

var backer=[],
    incentive=[],
    totalincentive=[];
for(var i=1;i<20;i++){
    backer[i] = document.getElementById("backer-prediction-"+i).value;
    incentive[i] = document.getElementById("incentive-cost-"+i).value;
    totalIncentive[i] = parseInt(backer[i],10) * parseInt(incentive[1],10);

    document.getElementById("incentive-total-"+i).value = totalIncentive[i];
}

So you can use them after ending for loop , like

backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]
于 2012-07-18T05:06:17.430 回答
3

Just like the last question, use a for loop:

for(var i = 1; i < 20; i++){
    var backer = document.getElementById("backer-prediction-"+i).value;
    var incentive = document.getElementById("incentive-cost-"+i).value;
    var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);

    document.getElementById("incentive-total-"+i).value = totalIncentive;
}
于 2012-07-18T05:06:53.923 回答
3
for (var i=1; i<=19; i++) {
    var backer = document.getElementById("backer-prediction-" + i).value;
    var incentive = document.getElementById("incentive-cost-" + i).value;
    var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
    document.getElementById("incentive-total-" + i).value = totalIncentive;
}

This untested code should be enough, unless you need access to the backer and incentive values for each one of the cases after the loop is completed.

于 2012-07-18T05:08:26.523 回答
0

If the value of backer and incentive is a number, I'd be tempted to do:

var get = document.getElementById;
var backer, incentive, totalIncentive = 0;

for(var i = 1; i < 20; i++) {
  totalIncentive += get("backer-prediction-" + i).value * get("incentive-cost-" + i).value;
}

as the multiplication will implicitly convert numeric strings to numbers. But you really should validate that the content of those elements is a valid number before doing anything, even if using parseInt.

于 2012-07-18T05:46:26.983 回答