JavaScript-更新订单总数/函数调用问题

时间:2018-06-30 19:07:46

标签: javascript function dom scope

我已经为此工作了两个小时,当我碰壁或炸了我的脑袋时,决定寻求帮助。

我正在使用电子商店结帐功能,但在获取DOM来获取信息和显示时遇到了麻烦。更具体地说,一旦用户选择一种送货方式,我就会尝试显示送货费用并更新ORDER TOTAL显示。

从下拉菜单中选择运输方式。

我需要帮助的是逻辑,代码放置策略。我的订单总额应该在DISPLAY CART函数中更新吗?在调用SHIPPING SELECTION函数后,如何将SHIPPINGPRICE变量馈入DISPLAY CART中?

   // Upon loading page from CART page - Display cart.
   displayCart();

   function displayCart() {
       var cartItem = JSON.parse(sessionStorage.getItem("cartSS"));
console.log(cartItem);
var cart = cartItem;

var productLine = document.getElementById('order-container');
var taxes=0, subTotal = 0, orderTotal = 0;

for (var j in cart) {
        var productName = productNameObj[cart[j].productID];
        var lineTotal = parseInt(cart[j].quantity) * (cart[j].price);

        subTotal+= lineTotal;

        productLine.insertAdjacentHTML('afterend', `<div class="product-line"><img id = "cart-img" src="img/${cart[j].productID}.jpg" alt="cart"><div id = "cart-product"><p id = "product-name">${productName}</p><p id = "product-size">Size: ${cart[j].size}</p></div><p id = "product-price">(${cart[j].quantity}) x $${cart[j].price} = $${lineTotal.toFixed(2)}</p></div></div>`);
    }

taxes = subTotal * 0.07;
orderTotal = subTotal + taxes;
//NOT WORKING
//orderTotal = subTotal + shippingPrice + taxes;
document.getElementById('subtotal').textContent = "Subtotal: $" + subTotal;

document.getElementById('taxes').textContent = "Taxes: $" + taxes.toFixed(2);
document.getElementById('orderTotal').textContent = "Order Total: $" + orderTotal.toFixed(2);
   }

   //ONCLICK FUNCTION: collects shipping method selection
   document.querySelector('#payment-btn').addEventListener('click', 
    shipSelection);

    function shipSelection() {
var shipSelection = document.getElementById("shipMethodSelect").value;

var shippingData = {        '0' : [0, "N/A"],
    '1' : [4, "First Class (2-3 Day Shipping)"],
    '2' : [10, "Over-night (1 Day Shipping)"]
};

//console.log(shippingData[shipSelection][0]);
if (shipSelection == 0) {
    alert("Please select a shipping method to continue.");

} else { 
    //Send to Session Storage
    var shippingPrice = shippingData[shipSelection][0];
    //UNLOCK PAYMENT SECTION
    //unlockSection();
    console.log(shippingPrice);
    document.getElementById('shippingCost').textContent = "Shipping: $" + shippingPrice.toFixed(2);
}
return shippingPrice;
    }

0 个答案:

没有答案