js表格计算商品价格与数量
时间: 2024-01-15 22:03:04 浏览: 53
可以使用JavaScript来计算表格中商品价格与数量的乘积,具体实现步骤如下:
1. 在表格中添加商品价格和数量的输入框,并为它们添加类名或ID,以便于在JavaScript中获取。
2. 通过JavaScript获取表格中所有商品的价格和数量,并计算它们的乘积。可以使用DOM操作获取表格中的元素,或者使用jQuery等库简化代码。
3. 将每个商品的价格与数量的乘积相加,得到表格中所有商品的总价。可以将结果显示在页面上,或者发送给后台进行处理。
下面是一个简单的示例代码,可以根据实际需求进行修改:
HTML代码:
```
<table>
<tr>
<td>商品1</td>
<td><input type="number" class="price"></td>
<td><input type="number" class="quantity"></td>
<td><span class="subtotal"></span></td>
</tr>
<tr>
<td>商品2</td>
<td><input type="number" class="price"></td>
<td><input type="number" class="quantity"></td>
<td><span class="subtotal"></span></td>
</tr>
<tr>
<td colspan="3">总价:</td>
<td><span id="total"></span></td>
</tr>
</table>
```
JavaScript代码:
```
$(function() {
$('.price, .quantity').on('input', function() {
var $row = $(this).closest('tr');
var price = parseFloat($row.find('.price').val()) || 0;
var quantity = parseInt($row.find('.quantity').val()) || 0;
var subtotal = price * quantity;
$row.find('.subtotal').html(subtotal.toFixed(2));
updateTotal();
});
function updateTotal() {
var total = 0;
$('.subtotal').each(function() {
total += parseFloat($(this).html()) || 0;
});
$('#total').html(total.toFixed(2));
}
});
```
这段代码使用了jQuery库来简化DOM操作,当商品的价格或数量发生变化时,会重新计算每个商品的小计,并更新总价。你可以根据实际需求进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)