用jquery写一个有两行商品信息的带有商品小计和价格总计和数量总计的一个简单页面,商品小计的功能为,商品小计是用数量乘单价以文本的形式保存到一个盒子里,数量的标签是input标签用number属性并且min=1,第一个商品的默认不变单价是10保存在一个span盒子里,第二个商品的默认单价是20保存在另一个span盒子里,商品1和商品2的小计为对应的数量成对应的单价,因为是两行数据所以要实现价格总计和数量总计,要加两个input标签其属性为checkbox来判断,新建两个span来存放数量总计和价格总计,这两个span的作用为,放累加第一个和第二个商品的数量和累加第一个商品的小计和第二个商品的小计,如果取消勾选其中的一个checked则将新建的数量总计的span的内容转换成数字在与另一个商品数量相减重新存储在数量总计的span中,价格总计的span的span内容转换成数字与另一个商品小计相减重新重新存储在价格总计的span中,如果两个checked都被取消勾选则将数量总计的span内通和价格总计的span内容清空
时间: 2023-06-19 15:05:16 浏览: 57
<!DOCTYPE html>
<html>
<head>
<title>商品信息</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>商品1</td>
<td>
<input type="number" min="1" class="quantity1" value="1">
</td>
<td>
<span class="price1">10</span>
</td>
<td>
<span class="subtotal1">10</span>
</td>
</tr>
<tr>
<td>商品2</td>
<td>
<input type="number" min="1" class="quantity2" value="1">
</td>
<td>
<span class="price2">20</span>
</td>
<td>
<span class="subtotal2">20</span>
</td>
</tr>
<tr>
<td colspan="4">
<input type="checkbox" class="check1" checked>商品1
<input type="checkbox" class="check2" checked>商品2
</td>
</tr>
<tr>
<td colspan="2">
数量总计:<span class="total-quantity">2</span>
</td>
<td colspan="2">
价格总计:<span class="total-price">30</span>
</td>
</tr>
</table>
<script>
$(document).ready(function() {
// 初始化商品小计
$('.subtotal1').text($('.quantity1').val() * $('.price1').text());
$('.subtotal2').text($('.quantity2').val() * $('.price2').text());
// 商品1数量改变事件
$('.quantity1').on('input', function() {
if ($(this).val() < 1) {
$(this).val(1);
}
$('.subtotal1').text($(this).val() * $('.price1').text());
updateTotal();
});
// 商品2数量改变事件
$('.quantity2').on('input', function() {
if ($(this).val() < 1) {
$(this).val(1);
}
$('.subtotal2').text($(this).val() * $('.price2').text());
updateTotal();
});
// 商品1复选框改变事件
$('.check1').on('change', function() {
if (!$(this).prop('checked')) {
$('.quantity1').val(0);
} else {
$('.quantity1').val(1);
}
$('.subtotal1').text($('.quantity1').val() * $('.price1').text());
updateTotal();
});
// 商品2复选框改变事件
$('.check2').on('change', function() {
if (!$(this).prop('checked')) {
$('.quantity2').val(0);
} else {
$('.quantity2').val(1);
}
$('.subtotal2').text($('.quantity2').val() * $('.price2').text());
updateTotal();
});
// 更新数量总计和价格总计
function updateTotal() {
let totalQuantity = 0;
let totalPrice = 0;
if ($('.check1').prop('checked')) {
totalQuantity += parseInt($('.quantity1').val());
totalPrice += parseInt($('.subtotal1').text());
}
if ($('.check2').prop('checked')) {
totalQuantity += parseInt($('.quantity2').val());
totalPrice += parseInt($('.subtotal2').text());
}
$('.total-quantity').text(totalQuantity);
$('.total-price').text(totalPrice);
}
});
</script>
</body>
</html>