如何使用jquery编程和计算多个小计和总计?
我正在琢磨如何在jquery中做到这一点,我需要在没有任何插件的情况下做到这一点。设想一个书籍购物车,每次数量变化(使用选择下拉菜单)都会更新总价、grandtotal和隐藏的输入值如何使用jquery编程和计算多个小计和总计?,jquery,Jquery,我正在琢磨如何在jquery中做到这一点,我需要在没有任何插件的情况下做到这一点。设想一个书籍购物车,每次数量变化(使用选择下拉菜单)都会更新总价、grandtotal和隐藏的输入值 <table> <tr> <td class="qty"> <select class="item-1"> <option value="1">1</option> <optio
<table>
<tr>
<td class="qty">
<select class="item-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
...
</select>
</td>
<td class="product">
Book 1
</td>
<td class="price-item-1">
$20
</td>
<td class="total-item-1">
$20
</td>
</tr>
<tr>
<td class="qty">
<select class="item-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
...
</select>
</td>
<td class="product">
Book 2
</td>
<td class="price-item-2">
$10
</td>
<td class="total-item-2">
$10
</td>
</tr>
...
...
<tr>
<td colspan="3" align="right">
<strong>Grand Total:</strong>
</td>
<td class="grandtotal">
</td>
</tr>
</table>
<input type="hidden" id="qty-item-1" value="0" />
<input type="hidden" id="total-item-1" value="0" />
<input type="hidden" id="qty-item-2" value="0" />
<input type="hidden" id="total-item-2" value="0" />
1.
2.
3.
...
第一册
$20
$20
1.
2.
3.
...
第二册
$10
$10
...
...
总计:
这应该让您开始:
$("select").change(function() {
var qty = $(this).val();
// get the price cell by moving up a level and searching for
// the descendant with a class name beginning with `price'.
// Remove the dollar sign to do math
var price = $(this).closest("tr")
.find("td[class^=price]")
.html().split("$")[1];
// a quantity is a whole number but a price is a float
var total = parseInt(qty) * parseFloat(price);
// write the total for this book to the 'total' cell
$(this).closest("tr")
.find("td[class^=total]")
.html("$" + total);
// sum up all the totals
var grandTotal = 0;
$("td[class^=total]").each(function() {
grandTotal += parseFloat($(this).html().split("$")[1]);
});
// update the grandtotal cell to the new total
$(".grandtotal").html("$" + grandTotal);
});
换句话说,您需要:
1-从所选选项的值中获取数量
2-从同一行中以“price”开头的单元格中获取价格,将其乘以数量,并更新同一行的“total”单元格
3-(重新)计算总计(所有总计的总和),并将该值放入.grandtotal
单元格
在这里试试:如何在jQuery中做什么?如何添加数字?为什么在.split(“$”[1]中有1?它的含义是什么?