我设计了一个表格,您可以在其中添加动态行,用户可以为每行选择数量和价格。我有一系列非常简单的函数,允许我删除、清空整个表或计算插入的所有产品的总数。
到目前为止,一切正常,当我创建 3 行时,问题发生了,我将其添加到它们的每个值,然后我决定删除第二行并计算总数。正如您所看到的,计算是有缺陷的,实际上我只返回添加到表中的第一个产品的总计。我不明白为什么该脚本不能正常工作。谁能帮我解决这个问题吗?
<html>
<table style='width:100%' id='table'>
<tr>
<td colspan='3'><input type="button" style="background-color:#00FA9A" value="add product" onclick="add()" id="button"><input type="button" style="background-color:red" value="Delete all" onclick="deleteall()" id="button">
</td>
</tr>
<tr>
<td>Quantity</td>
<td>€</td>
<td>Delete</td>
</tr>
</table>
<input type="button" id="button" value="Calc total" onclick="total()"><input type="text" class='input' id="total">€
</html>
<script>
var idx = 0;
var cont = 0;
var buttcont = 0;
var quantity, priece;
function deleteall()
{
location.reload();
}
function add()
{
var tableRef = document.getElementById('table').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "row" + cont;
cont++;
var newCell1 = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var input1 = document.createElement('input'),
input2 = document.createElement('input');
input3 = document.createElement('button');
input1.type = 'number';
input1.style.width = "100%";
input1.id = "priece" + idx;
input1.min = 0;
input1.value = 1;
input2.type = 'text';
input2.min = 1;
input2.style.width = "100%";
input2.id = "quantity" + idx;
input3.class = 'button';
input3.innerHTML = "Delete";
if(input3.attachEvent) input3. attachEvent('onclick',function(e){deleted(e);})
else if(input3.addEventListener) input3.addEventListener('click',function(e){deleted(e);},false)
newCell1.appendChild(input1);
newCell2.appendChild(input2);
newCell3.appendChild(input3);
idx++;
}
function deleted(e)
{
if(document.removeChild && document.getElementById && document.getElementsByTagName)
{
if(!e) e = window.event;
var srg = (e.target)?e.target:e.srcElement;
while(srg.tagName != "TR"){srg = (srg.parentNode)?srg.parentNode:srg.parentElement}
var tb = document.getElementById('table').getElementsByTagName('TBODY')[0];
tb.removeChild(srg);
cont--;
idx--;
}
}
function total()
{
var total = 0;
for(var i = 0; i < idx; i++)
{
quantity = document.getElementById('quantity' + i).value;
priece = document.getElementById('priece' + i).value;
total += quantity * priece;
document.getElementById('total').value = total;
}
}
最佳答案
问题来自这样一个事实:当您删除表中的一行(而不是最后一行)时,ID 中有一个间隙。 getElementById
将返回 null
并且您的 total
函数将引发异常。
- 添加3个产品:idx为3,DOM中的ids为0,1,2;
- 删除产品1:idx为2,DOM中的ids为0, 2; => 当 i == 1 时,总计将抛出
实际上,您可以通过为输入分配一个类来避免循环 ids。 Demo .
function total()
{
var total = 0,
prices = document.querySelectorAll('.price'),
quantities = document.querySelectorAll('.quantity'),
i = 0, len = prices.length;
for(; i < len; i++) {
total += prices[i].value*quantities[i].value;
}
document.getElementById('total').value = total;
}
关于javascript - 动态表中总计计算中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24714164/