gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:56:02 25 4
gpt4 key购买 nike

我是 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. 如果购物车中没有内容并且 addToCartsome action 被调用,所以基本上这里我们需要检查购物车的当前状态,这是通过调用 getCartItems 获得的,如果它是Null,如果调用addToCart,我们就会执行某些操作
  2. 购物车中是否有内容并且 addToCartsome action 被调用,所以基本上这里我们需要检查购物车的当前状态,这是通过调用 getCartItems 获得的并检查如果它是 Null 或不是,并且如果调用 addToCart ,那么如果购物车中有一些内容,我们会执行某些操作
  3. 购物车中是否有内容并且 removeFromCart 被称为 some action,所以基本上这里我们需要检查购物车的当前状态,这是通过调用 getCartItems 获得的,如果它不为 Null,如果调用了 removeFromCart ,我们就会执行某些操作

我想要做的事情的伪代码:

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

}
}

关于javascript - jQuery:我们如何实现 if...else 逻辑和调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2618979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com