繁体   English   中英

jQuery:如果……其他逻辑和调用函数,我们如何实现

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

我是jQuery的新手,所以如果听起来很蠢,就不要介意这个问题,但这是我要尝试做的事情:

我有3个功能,例如:

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()
    {
    }

现在我正在尝试做三件事:

  1. 如果cart中没有content ,并且addToCart而不是执行some action ,那么基本上在这里,我们需要检查cart的当前状态,该状态是通过调用getCartItems获得的,如果它为Null并且如果addToCart则执行some action
  2. 如果购物车中有content并且addToCart而不是执行some action ,那么基本上在这里,我们需要检查购物车的当前状态,该状态是通过调用getCartItems获得的,并检查它是否为Null以及是否比我们调用addToCart如果购物车中有一些内容,请执行some action
  3. 如果购物车中有content ,并且removeFromCart被称为some action ,那么基本上在这里我们需要检查购物车的当前状态,这是通过调用getCartItems获得的,如果它不是Null,并且如果调用removeFromCart则我们将执行some action

我正在尝试做的伪代码:

    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(
            );

我的基本担心是对jQuery和JavaScript完全是新手,因此不确定如何实现if ... else逻辑以及如何使用jQuery / JavaScript调用函数。

它与任何其他编程语言相似。

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

但是,由于必须在addToCartremoveFromCart时执行这些操作,因此一个简单的解决方案是将这些条件放入函数本身中:

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) {

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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