两个页面实现购物车html
时间: 2023-09-16 09:06:33 浏览: 179
页面1:商品列表页面
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品列表</title>
</head>
<body>
<h1>商品列表</h1>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>商品1</td>
<td>100</td>
<td><button onclick="addToCart('商品1', 100)">加入购物车</button></td>
</tr>
<tr>
<td>商品2</td>
<td>200</td>
<td><button onclick="addToCart('商品2', 200)">加入购物车</button></td>
</tr>
<tr>
<td>商品3</td>
<td>300</td>
<td><button onclick="addToCart('商品3', 300)">加入购物车</button></td>
</tr>
</tbody>
</table>
<script>
function addToCart(name, price) {
var cart = JSON.parse(localStorage.getItem('cart')) || [];
cart.push({ name, price });
localStorage.setItem('cart', JSON.stringify(cart));
alert('已成功添加到购物车!');
}
</script>
</body>
</html>
```
页面2:购物车页面
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物车</title>
</head>
<body>
<h1>购物车</h1>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody id="cart">
</tbody>
</table>
<script>
var cart = JSON.parse(localStorage.getItem('cart')) || [];
var cartTable = document.getElementById('cart');
cart.forEach(function(item) {
var row = cartTable.insertRow();
var nameCell = row.insertCell();
var priceCell = row.insertCell();
nameCell.appendChild(document.createTextNode(item.name));
priceCell.appendChild(document.createTextNode(item.price));
});
</script>
</body>
</html>
```
在以上代码中,第一个页面展示了商品列表,每个商品都有一个“加入购物车”的按钮,点击按钮可以将商品加入购物车。点击按钮时,会执行`addToCart`函数,该函数将商品信息存储到本地存储中。
第二个页面展示了购物车列表,它从本地存储中获取购物车中的商品信息,并展示在页面上。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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://img-home.csdnimg.cn/images/20241231044955.png)