2013-06-05 13 views
0

我有一個JavaScript函數象下面這樣:的Javascript循環警報僅第一指數

function calculateBill(id,price) 
{ 
    var qty = document.getElementById('qty_'+id).value; 
    var cur_value =qty*price;  
    var frm_lngth = document.getElementById('bnfsendgoods').length;  
    var fld_length1 = Number(frm_lngth) - 10;  
    var counter = document.getElementById('cntr').value;   
    var fld_length = (Number(fld_length1))/(Number(counter));  
    fld_length = Number(fld_length);   
    var temp_total = 0; 

    alert(fld_length); 

    for(var i = 1; i<=fld_length; i++) 
    { 
     if(i != id) 
     { 

      alert('qty_'+i); //line 301,alerts only qty_1   

      var temp_q = document.getElementById('qty_'+i).value; 
    var temp_p = document.getElementById('ret_price_'+i).value; //Line 308 
      var temp_total1 = temp_q*temp_p;    
      temp_total = Number(temp_total) + Number(temp_total1); 
     } 
    } 

    var final_total = Number(cur_value) + Number(temp_total); 
    document.getElementById('total').value = final_total; 
} 

在線路301,alert(fld_length);警報8。如果假設id = 3,根據我的邏輯,應該有 這樣的提醒,如qty_1,qty_2,qty_4,qty_5,qty_6等等。但它僅提醒qty_1。怎麼了?

+0

alert(fld_length); alert?一些HTML代碼也可能有助於發現問題。 – gkalpak

+0

你有任何支持HTML嗎? – Bloafer

+0

'alert(fld_length);'alerts'8'。 – Nitish

回答

1

從你的評論,你必須輸入字段:

<input type="hidden" name="ret_price_0" value="20" /> 
<input type="hidden" name="ret_price_1" value="20" /> 
etc. 

這些字段不具有id屬性,但你與試圖通過id選擇它們:

var temp_p = document.getElementById('ret_price_'+i).value; 

document.getElementById('ret_price_'+i)沒有按找到具有指定的id的元素,則返回null,然後null.value給出Uncaught TypeError: Cannot read property 'value' of null

指定適當的id屬性,並且您的代碼應該可以工作。 (而且要小心,我注意到你輸入的name屬性在0結束,但你的循環從1fld_length。)

而作爲一個旁白:你已經得到了太忘乎所以與​​方法 - 你不需要在已經包含數字的變量上使用它。你應該在用戶輸入的值上使用它(如果用戶輸入的不是數字,你應該考慮顯示錯誤信息),因爲當你得到一個輸入文本.value時,它會以字符串形式出現,但你不會無處不需要​​

0

for循環中可能會發生異常,導致循環過早終止。可以嘗試將try/catch中的代碼塊放入循環中,以便了解發生了什麼問題。

+0

如果使用瀏覽器的控制檯進行調試,則不需要try/catch塊。但是,無論如何,這並不能真正回答問題,所以應該作爲評論發佈。 – nnnnnn