2012-07-18 68 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,您確實應該在做任何事情之前驗證這些元素的內容是否是有效的數字。