如何简化这个JavaScript

时间:2012-07-18 05:02:37

标签: javascript

  

可能重复:
  Any way to simplify this code?

从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;

我发布的最后一个他们给了我一个“for”循环。

还在学习这些东西..很新,谢谢!!!

4 个答案:

答案 0 :(得分:3)

在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];
}

所以你可以在结束循环后使用它们,比如

backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]

答案 1 :(得分:3)

last question一样,请使用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;
}

答案 2 :(得分: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;
}

这个未经测试的代码应该足够了,除非您需要在循环完成后访问每个案例的backerincentive值。

答案 3 :(得分:0)

如果支持者激励的值是一个数字,我很想做:

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;
}

因为乘法会隐式地将数字字符串转换为数字。但是你真的应该在做任何事情之前验证这些元素的内容是有效数字,即使使用 parseInt