需求分析
我希望网页首部为大标题,中间部分摆放商品,尾部购物车结算价格。
目标实现
HTML代码部分不做过多赘述,前面几篇已经说的很多了,都是类似的内容。唯一要注意的是先创建两个容器,分别放产品和购物单。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple E-commerce Site</title>
<link rel="stylesheet" href="product.css">
</head>
<body>
<header>
<h1>Simple E-commerce Site</h1>
</header>
<div id="products">
<!-- Products will be loaded here -->
</div>
<h2>Shopping Cart</h2>
<div id="cart">
<!-- Cart items will be displayed here -->
</div>
<script src = "product.js"> </script>
</body>
</html>
要实现购物的功能,首先要有商品,这里我们通过const常量的方式来定义,形式如下:
const products = [
{ id: 1, name: 'Product 1', price: 100},
// ... 略
];
首先需要让用户能够看到商品,定义renderProducts()函数,在页面上渲染产品列表。再遍历产品数组,为每个产品创建一个包含链接、价格、添加按钮的HTML结构,并将每个产品的HTML结构添加到product元素中。当然,这里的链接我们会在之后再讲。
function renderProducts() {
const productsElement = document.getElementById('products');
productsElement.innerHTML = '';
products.forEach(product => {
const productLink = document.createElement('a');
productLink.href = product.href;
productLink.className = 'product-link';
productLink.innerHTML = `
<div class="product">
<h3>${product.name}</h3>
<p>Price: $${product.price}</p>
<button class="add-to-cart-btn" onclick="