2012-07-18 67 views
-1

可能重复:
Any way to simplify this code?如何简化这个JavaScript

什么是简化这种从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

而“for”循环在这种情况下也不起作用? – pagliuca 2012-07-18 05:04:20

+0

for循环用于其他代码,我不知道如何将其应用于此:/ – Reuben 2012-07-18 05:05:41

+0

与此处所做的相同。 – 2012-07-18 05:05:53

回答

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

谢谢!你从变量支持者和totalIncentive中删除了1,是否应该从发明中删除? – Reuben 2012-07-18 05:08:32

+1

@Reuben:这并不重要,但要保持一致,是的。凌晨1点,所以我只是错过了它。 – 2012-07-18 05:09:47

+0

我在答案中删除了数字,因为它们对于作为数组进行存储并不重要。如果您需要为每个元素获取确切的值,Will只需要将其存储为数组。 – pagliuca 2012-07-18 05:10:51

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] 
+0

我在Dreamweaver的var backer ...行中遇到错误:/ – Reuben 2012-07-18 05:14:15

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值。

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,您确实应该在做任何事情之前验证这些元素的内容是否是有效的数字。