21xrx.com
2025-03-29 03:26:56 Saturday
文章检索 我的文章 写文章
用JavaScript实现简易购物车
2023-06-17 00:47:59 深夜i     12     0

我最近在学习JavaScript,在尝试用它来开发一个简易的购物车应用。经过一番摸索,我终于成功了!下面我来分享一下我的经验和代码。

首先是HTML和CSS的部分,我没有用任何框架,只是写了一个基本的网页结构,并在样式中设置了购物车表格的样式。代码如下:

JavaScript Simplified Shopping Cart
   
 
 
 
  
My Simple Shopping Cart
  
   
    
    
    
    
   
   
    
    
    
    
   
   
    
    
    
    
   
   
    
    
    
    
   
   
    
    
   
  

 
  
   Product
   Price
   Quantity
   Total
  
  
   Product 1
   $10.99
   
   $0.00
  
  
   Product 2
   $5.99
   
   $0.00
  
  
   Product 3
   $8.49
   
   $0.00
  
  
   Total:
   $0.00
  
 

  Calculate

CSS:

body
 font-family: sans-serif;
 margin: 0;
 padding: 0;
h1
 font-size: 30px;
 text-align: center;
table
 width: 80%;
 border-collapse: collapse;
 margin: auto;
table th,
table td
 border: 1px solid #ccc;
 padding: 10px;
 text-align: center;
table th
 background-color: #eee;
 font-weight: bold;
table input[type="number"]
 width: 70px;
table td.total
 font-weight: bold;
#total
 font-size: 20px;
 font-weight: bold;
 text-align: right;
 padding: 10px;
 color: #c00;

然后是JavaScript的部分。我定义了一个数组,其中存储了每个商品的价格和数量。在点击“Calculate”按钮时,程序会遍历数组,计算出每个商品的总价,最后再计算出整个购物车的总价,并将结果显示在页面上。

代码如下:

const products = [
  price: 10.99,
  quantity: 0 ,
  price: 8.49
];
function calculateTotal() {
 let total = 0;
 for (let i = 0; i < products.length; i++) {
  let productTotal = products[i].price * products[i].quantity;
  let cell = document.getElementsByClassName("total")[i];
  cell.innerHTML = "$" + productTotal.toFixed(2);
  total += productTotal;
 }
 document.getElementById("total").innerHTML = "$" + total.toFixed(2);
}
document.getElementById("calculate").addEventListener("click", calculateTotal);
document.querySelectorAll(".quantity").forEach((element, index) => {
 element.addEventListener("change", () => {
  products[index].quantity = parseInt(element.value);
 });
});

以上就是我实现简易购物车的代码和思路,希望对大家有所帮助。本例中的三个关键词是JavaScript、购物车、数组。

  
  

评论区