简体   繁体   中英

jQuery: How can we implement if…else logic and call function

I am new to jQuery and so don't mind this question if it sounds stupid but here is something that I am trying to do :

I have 3 functions like:

AddToCart Function which adds item to the shopping cart:
//offer_id is the offer which we are trying to add to cart. 
    addToCart: function(offer_id)
    {
    },


RemoveFromCart which removes data from the cart
//target is link clicked and event is the click event. 
    removeFromCart: function(target, event)
    {
    },

Get the current state of the cart   
//return string which represents current state of cart. 
    getCartItems: function()
    {
    }

Now I am trying to do 3 things:

  1. if there is no content in cart and addToCart is called than some action , so basically here we need to check the current state of cart and that is obtained by calling getCartItems and if it is Null and than if addToCart is called than we perform some action
  2. if there is content in the cart and addToCart is called than some action ,so basically here we need to check the current state of cart and that is obtained by calling getCartItems and check if it is Null or not and than if addToCart is called than we perform some action if we had some content in the cart.
  3. if there is content in the cart and removeFromCart is called some action , so basically here we need to check the current state of cart and that is obtained by calling getCartItems and if it is not Null and if removeFromCart is called than we perform some action

Pseudocode of what I am trying to do:

    if there is no content in cart 
        and addToCart is called than 
        $(document).track(
            );

    if there is content in the cart 
        and addToCart is called than
        $(document).track(
            );

    if there is content in the cart 
        and removeFromCart is called 
        $(document).track(
            );

My basic concern is that am complete newbie to jQuery and JavaScript and so am not sure how can I implement if...else logic and how can I call a function using jQuery/JavaScript.

It's similar to any other programming language.

if() {
    ..
}
else if() {
    ..
}
else if() {
    ..
}

However, since these actions have to be performed when addToCart and removeFromCart are called, a simple solution is to put those conditions inside the functions itself:

addToCart: function(offer_id) {
    // add to cart is called and cart IS empty
    if(this.getCartItems().length == 0) {

    }
    // add to cart is called and cart is NOT empty
    else {

    }
}

removeFromCart: function(target, event) {
    // remove was called and cart has items
    if(this.getCartItems().length > 0) {

    }
}

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