Javascript 如何制作js计算篮子中的价格
我想计算购物车中所选项目的成本。Ie我有一个产品列表,在复选框旁边。如果此复选框被激活,则此产品的成本将添加到总成本中。如果从产品中删除复选框,则此产品的价格将从总成本中删除。 我的html代码:Javascript 如何制作js计算篮子中的价格,javascript,html,thymeleaf,Javascript,Html,Thymeleaf,我想计算购物车中所选项目的成本。Ie我有一个产品列表,在复选框旁边。如果此复选框被激活,则此产品的成本将添加到总成本中。如果从产品中删除复选框,则此产品的价格将从总成本中删除。 我的html代码: <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8&
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span id="totalPrice"></span>
<div th:if="${orderError}">
<div style="color: red" th:text="${orderError}"></div>
</div>
<form th:action="@{/order}">
<div th:each="product : ${session.bucket}">
Product #<span th:text="${productStat.index + 1}"></span></h5>
<div th:if="${product.quantity == 0}">
<div style="color: red">The product is over</div>
</div>
<p>
Brand : <span th:text="*{product.brandName}"></span>
</p>
<p>
Model : <span th:text="*{product.model}"></span>
</p>
<p>
Season : <span th:text="*{product.seasonName}"></span>
</p>
<p>
Color : <span th:text="*{product.colorName}"></span>
</p>
<p>
Material : <span th:text="*{product.materialName}"></span>
</p>
<p>
Size : <span th:text="*{product.size}"></span>
</p>
<p>
Category : <span th:text="*{product.categoryName}"></span>
</p>
<p>
Price : <span th:id="'productId' + ${product.id}" th:text="*{product.price}"></span>
</p>
<div>
<img th:src="*{product.url}"
width="189" height="255" alt="lorem">
</div>
<p><a th:href="@{/bucket/delete/{id}(id=${product.id})}">Delete from cart</a></p>
<div th:if="${product.quantity != 0}">
<input type="checkbox" name="selected" th:value="${product.id}">
</div>
</div>
<input name="submit" type="submit" value="Make order" />
</form>
<p><a th:href="@{/}">Home</a></p>
</body>
</html>
您的标记不利于获得清晰的答案,因此我将其缩减,并添加了第二个复选框作为示例。因为您使用了它,所以我将jQuery添加到代码段中
“myproduct”
类data
属性的“price”类元素来保存price值data product price=“34.29”
——例如,允许我使用$
格式化元素的文本。这很可能会出现在复选框中——即使是实际的“值”,但仍保留在示例代码中let box=$('input[type=checkbox].mything')
设totalPrice=$(“#totalPrice”);
box.on('change',function(){
设boxesPrice=0;
box.filter(':checked')。每个(函数(){
让productPrice=$(此)
.closest(“.myproduct”)
.find(“.price”)
.数据(“产品价格”);
BoxesSprice+=parseFloat(产品价格);
});
totalPrice.text(boxesPrice.toFixed(2));
});代码>
产品#有趣的家伙
价格:$34.29
产品#胡萝卜
价格:$7.84
$(function(){
var totalPrice = $('#totalPrice');
var boxes = $('input[type=checkbox]')
var totalPriceNow = 0;
boxes.click(function() {
totalPriceNow = 0;
boxes.each(function() {
if (this.checked) {
var productId = 'productId';
productId += this.value;
var productPrice = $('#' + 'productId').text();
totalPriceNow += parseInt(productPrice);
}
});
totalPrice.text(totalPriceNow);
});
})