jQuery:我们如何实现if ... else逻辑和调用函数

时间:2010-04-11 22:38:27

标签: javascript jquery

我是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. 如果购物车中没有content 而且addToCart的调用次数比some action要大,所以基本上我们需要检查购物车的当前状态,这是通过调用getCartItems获得的,如果是Null而不是addToCart调用some action比我们执行content
  2. 如果购物车中有addToCart some action被调用而getCartItems被调用,所以基本上我们需要检查购物车的当前状态,并通过调用Null并检查它是否为addToCart来获取如果我们在购物车中有一些内容,那么如果调用some action,我们会执行content
  3. 如果购物车中有removeFromCart 而且some action被称为getCartItems,所以基本上我们需要检查购物车的当前状态,这是通过调用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( );
  4. 我正在尝试做的伪代码:

    {{1}}

    我最基本的担心是jQuery和JavaScript的新手,所以我不知道如何实现if ... else逻辑以及如何使用jQuery / JavaScript调用函数。

1 个答案:

答案 0 :(得分:1)

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

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

    }
}