用html设计一个能根据用户输入的商品编号和数量,计算总价并显示清单的程序。
时间: 2024-06-10 12:10:25 浏览: 10
<!DOCTYPE html>
<html>
<head>
<title>购物清单</title>
<meta charset="UTF-8">
</head>
<body>
<h1>购物清单</h1>
<form>
<label for="product-id">请输入商品编号:</label>
<input type="text" id="product-id" name="product-id"><br><br>
<label for="product-quantity">请输入商品数量:</label>
<input type="number" id="product-quantity" name="product-quantity"><br><br>
<input type="button" value="计算总价" onclick="calculatePrice()">
</form>
<br>
<h2>清单</h2>
<table id="shopping-list">
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
<th>商品总价</th>
</tr>
</table>
<h2 id="total-price"></h2>
<script>
function calculatePrice() {
var productID = document.getElementById("product-id").value;
var productQuantity = document.getElementById("product-quantity").value;
var productList = [
{
id: "001",
name: "商品A",
price: 10
},
{
id: "002",
name: "商品B",
price: 20
},
{
id: "003",
name: "商品C",
price: 30
}
];
var product = productList.find(function(item) {
return item.id === productID;
});
if (product === undefined) {
alert("商品编号不存在,请重新输入!");
return;
}
var productName = product.name;
var productPrice = product.price;
var productTotalPrice = productPrice * productQuantity;
var table = document.getElementById("shopping-list");
var row = table.insertRow(-1);
var idCell = row.insertCell(0);
var nameCell = row.insertCell(1);
var priceCell = row.insertCell(2);
var quantityCell = row.insertCell(3);
var totalPriceCell = row.insertCell(4);
idCell.innerHTML = productID;
nameCell.innerHTML = productName;
priceCell.innerHTML = productPrice;
quantityCell.innerHTML = productQuantity;
totalPriceCell.innerHTML = productTotalPrice;
var totalPrice = 0;
for (var i = 1; i < table.rows.length; i++) {
totalPrice += parseInt(table.rows[i].cells[4].innerHTML);
}
document.getElementById("total-price").innerHTML = "总价:" + totalPrice;
}
</script>
</body>
</html>
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)