2017-07-14 64 views
0

對不起,這只是一個簡單的問題。問題是總金額只計算一行。它只計算被點擊的特定產品的一行。那麼,如何計算所有行的總量呢?爲什麼總計僅在一行上計算

const cart = {}; 
 
let GrandTotal = 0; 
 

 
function AddtoCart(productid, description, quantity, price) { 
 
    if (cart[productid]) { 
 
    cart[productid].qty += quantity; 
 
    } else { 
 
    cart[productid] = { 
 
     id: productid, 
 
     desc: description, 
 
     qty: quantity, 
 
     price: price 
 
    }; 
 
    } 
 
    
 
    viewCart(); 
 
    
 
    
 
    GrandTotal += parseFloat(cart[productid].price) * parseInt(cart[productid].qty); 
 
    document.getElementById("total").innerHTML = GrandTotal; 
 
    console.log(GrandTotal); 
 
    
 
    } 
 

 
function viewCart() { 
 
    let tbody = document.getElementById('cartsBody'); 
 
    tbody.innerHTML = ''; 
 
    Object.values(cart).forEach(content => { 
 
    tbody.innerHTML += `<td>${ content.id }</td> 
 
         <td>${ content.desc }</td> 
 
         <td>${ content.qty }</td> 
 
         <td>${ content.price }</td> 
 
         <td>${ content.qty * content.price }</td>`; 
 

 

 
    }); 
 
    
 
}
<script src="script.js"></script> 
 

 
<input type="button" value="Laptop" onclick="AddtoCart('132','Macbook Pro', 1, 79000,0)" /> 
 
<input type="button" value="Phone" onclick="AddtoCart('456','Iphone 5S', 1, 18000,0)" /> 
 
<input type="button" value="Camera" onclick="AddtoCart('789','Nikon 3D00', 1, 25000,0)" /> 
 

 
<table border="1|1" id="cartsTable"> 
 
    <thead> 
 
    <tr> 
 
     <th>Product ID</th> 
 
     <th>Product Description</th> 
 
     <th>Quantity</th> 
 
     <th>Price</th> 
 
     <th>Total</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody id="cartsBody"> 
 
    </tbody> 
 
</table> 
 
<p id="total">Total: </p>

回答

1

我每次都會從購物車數據中重新計算總計,而不是每當您點擊某個產品時嘗試添加。您可能還想稍後移除項目。

function calculateGrandTotal(){ 
    GrandTotal = 0; 
    for(let productid in cart){ 
     if(cart.hasOwnProperty(productid)){ 
      GrandTotal += parseFloat(cart[productid].price) * parseInt(cart[productid].qty); 
     } 
    } 
} 

而在你AddToCart功能,您只需要調用的計算功能:

function AddtoCart(productid, description, quantity, price) { 
    // [...] 
    calculateGrandTotal(); 
    document.getElementById("total").innerHTML = GrandTotal; 
    console.log(GrandTotal); 
} 
+0

謝謝。請提出我的問題 – Joseph

0

點擊每次addToCart,設置grandtotal爲零。

在點擊功能之外初始化您的grandtotal變量。

+0

你總是加總所選擇的類型總計所有產品,而不只是一個補充。例如:購物車中已經有1臺相機。如果您添加另一臺相機,它會將兩臺相機的價格添加到總計而不是一臺。 – Danmoreng

+0

@丹莫朗。那麼我將如何解決這個問題?我知道的邏輯,但不能寫在代碼 – Joseph