[英]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()
{
}
現在我正在嘗試做三件事:
content
,並且addToCart
而不是執行some action
,那么基本上在這里,我們需要檢查cart的當前狀態,該狀態是通過調用getCartItems
獲得的,如果它為Null
並且如果addToCart
則執行some action
content
並且addToCart
而不是執行some action
,那么基本上在這里,我們需要檢查購物車的當前狀態,該狀態是通過調用getCartItems
獲得的,並檢查它是否為Null
以及是否比我們調用addToCart
如果購物車中有一些內容,請執行some action
。 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() {
..
}
但是,由於必須在addToCart
和removeFromCart
時執行這些操作,因此一個簡單的解決方案是將這些條件放入函數本身中:
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.