简体   繁体   中英

Applying discount to Javascript cart

I am trying to have a discount applied to this file/shopping cart. I am able to get the discount function working but it continuously removes the total instead of only once. Any suggestions?

function totalCost(product, action) {
    let cartCost = localStorage.getItem('totalCost');
    
    console.log("My cartCost is", cartCost);
    console.log(typeof cartCost );
    if(action == "decrease") {
        cartCost = parseInt(cartCost);
        localStorage.setItem('totalCost',cartCost - product.price);
    } else if(cartCost != null) {
        cartCost = parseInt(cartCost);
        localStorage.setItem("totalCost", cartCost + product.price);
    } else {
        localStorage.setItem("totalCost", product.price);
    }
}

function discountCart() {
    let cartCost = localStorage.getItem('totalCost');

    // VARIABLES FOR 20 OR 50
    var discount20 = parseInt(cartCost) - 20
    var discount50 = parseInt(cartCost) - 50
    
    console.log("My cartCost is", cartCost);
    console.log(typeof cartCost );

    // DISCOUNT FUNCTIONALITY
    if (cartCost >= 50 || cartCost <= 75) {
        localStorage.setItem("totalCost", cartCost = discount20)
        console.log('discount 20!', cartCost = discount20)
    } else if (cartCost >= 200 || cartCost <= 250){
        localStorage.setItem("totalCost", cartCost = discount50)
        console.log('discount 50!', cartCost = discount50)
    };
}

At:

// VARIABLES FOR 20 OR 50
var discount20 = parseInt(cartCost) - 20
var discount50 = parseInt(cartCost) - 50

Instead of using the - operator use the -= instead, like so:

// VARIABLES FOR 20 OR 50
var discount20 = parseInt(cartCost) -= 20
var discount50 = parseInt(cartCost) -= 50

Also, at:

localStorage.setItem('totalCost',cartCost - product.price);

Do the same:

localStorage.setItem('totalCost',cartCost -= product.price);

Likewise replace every + operator with += in your code.

Also, carefully read:

https://www.w3schools.com/js/js_operators.asp

to understand javascript operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM