Javascript循环警报只针对第一个索引
Javascript loop alert only first index
我有一个像下面这样的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);
发出警报。假设是id = 3
,根据我的逻辑,应该是如qty_1
、qty_2
、qty_4
、qty_5
、qty_6
等。但它只提醒qty_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
结束,但你的循环从1
到fld_length
。)
作为题外话:你已经对Number()
方法太着迷了——你不需要在已经包含数字的变量上使用它。应该在用户输入的值上使用(如果用户输入的不是数字,则应该考虑显示错误消息),因为当您获得带有.value
的输入文本时,它以字符串的形式出现,但您不需要到处都使用Number()
for循环中可能发生异常,导致循环过早终止。可以尝试将代码块放入try/catch的循环中,这样您就可以知道哪里出了问题。
相关文章:
- Javascript:foreach跳过第一个索引(0)
- Jqgrid在第一个下拉索引chnage方法后未重新加载
- 正在查找数组中第一个匹配元素的索引
- 为什么不't此循环返回到第一个索引
- 如何使用javascript从包含数值的字符串中获取第一个字符的索引
- 选择下拉列表值而不是第一个索引的任何解决方案
- 将两个数组中的项目合并到第三个数组中,其中一列从第一个数组中减去第二个索引
- 在索引之后查找字符串的第一个索引
- 如何将第一个元素的 .index() 的默认索引 0 更改为 1
- Javascript/Jquery:在嵌套数组中查找具有键值对的第一个和最后一个数组的索引的最有效方法
- DOJO DataGrid-如何获取第一个可见行和最后一个可见行的索引(编号)
- 为什么我的函数只在JavaScript中将第一个索引连接到数组中
- 基于第一个索引过滤二维javascript数组
- JSON获取第一个索引名
- Javascript循环警报只针对第一个索引
- For循环只对第一个索引起作用
- 尝试从状态数组从索引进行拼接,但最终从第一个索引拼接到最后一个索引
- 我如何引用点击第一<光>到另一个数组的第一个索引,依此类推
- jquery中的Json第一个索引值获取
- 将数组值推到第一个索引