0

我正在创建一个简单的购物车原型,并希望创建一个 JavaScript 数组,该数组将获取每个表格行的数量,将其乘以价格,并在最后一列中显示总数。数量值是用户输入数量的一种形式。我还想在总计中包含一个表格行。我有这两个功能,但我想知道如何使一个功能适用于整个表格:

<script type="application/javascript">
 function total()
 {
var qty = document.forms["qty"]["amount"].value;
var sum1 = qty * 5.99;
document.getElementById("total1").innerHTML="$" + sum1;
 }
</script>

<script type="application/javascript">
 function total2()
 {
var qty2 = document.forms["qty2"]["amount2"].value;
var sum2 = qty2 * 105.99;
document.getElementById("total2").innerHTML="$" + sum2;
 }
</script>

桌子

<table id="cart">
<tr>
<th><b>Quantity</b></th>
<th><b>Item</b></th>
<th>Price</b></th>
<th><b>Total</b></th>          
</tr> 
<tr>
<td><form name="qty"><input type="number" name="amount" size="1" value="1" onchange="total1()"/></form></td>
<td>Product 1</td>
<td>$5.99</td>
<td id="total1"></td>
</tr>
<tr>
<td><form name="qty2"><input type="number" name="amount2" size="1" value="1" onchange="total1()"/></form></td>
<td>Product 2</td>
<td>$105.99</td>
<td id="total2"></td>
</tr>
<tr>
<td><b>Grand Total<b></td>
<td id="grand"></td>
</tr>
</table>
4

2 回答 2

0

Remove the inline onchange event from both number type inputs and paste following code inside head tags between script tags

(function grandTotal()
{
    var cart=document.getElementById('cart'),
    forms=cart.getElementsByTagName('form'), total=0;
    for(var i=0;i<forms.length;i++)
    {
        var amount=forms[i].getElementsByTagName('input')[0];
        var qty=amount.value;
        var tr=forms[i].parentNode.parentNode;
        var price=tr.getElementsByTagName('td')[2].innerHTML.substr(1);
        total+=parseFloat(qty)*parseFloat(price);
        amount.onchange=grandTotal;
    }
    document.getElementById('grand').innerHTML=total.toFixed(2);
})();

Example Here.

于 2012-12-12T23:31:22.537 回答
0

您可以为每个表设置一个 id 并将其传递给函数:

<script type="application/javascript">
function total(i, value)
{
    var qty = document.forms["qty" + i]["amount" + i].value;
    var sum1 = qty * value;
    document.getElementById("total" + i).innerHTML="$" + sum1;
}
</script>

因此,在 onChange 调用 total('1', '5.99') 和 total('2', '105.99')。

使用 JQuery 更容易使用 'this' + 选择器

于 2012-12-12T22:41:41.183 回答