[英]Need to add and delete items from a Shopping Cart using javascript/jQuery
[英]Javascript: Subtracting items from shopping cart result in negative value
我有要修改的購物車腳本。 麻煩的是,每當我嘗試從購物車中刪除多個項目時,我都會得到一個負值。 刪除所有物品后,購物車永遠不會歸零。 我可以添加項目。
下面是此功能的代碼段。 完整的代碼在擺弄中,因為通過向您展示我所遇到的問題的演示更容易解釋。
function addToCart(id, container_id, corTitle, corPrice, credit_hrs) {
var amount = parseFloat(corPrice);
var hours = parseFloat(credit_hrs);
var remove = "<button type=\"button\" class=\"remove\"></button>";
var selected_product = "<div class=\"item \">"
+ "<div class=\"title\">"
+"<div class=\"remove\"><button type=\"button\" title=\"remove from cart\" class=\"remove-from-cart\" alt=\"Remove Course\" ></button></div>"
+ corTitle
+ " for $" + corPrice
+ "</div>"
+ "<input name=\"containerId\" value=\"" + container_id
+ "\" type=\"hidden\">" + "</div>";
$(selected_product).insertBefore("#subtotals");
register("add", amount, hours);
$(".remove-from-cart").click(function() {
$(this).parents(".item").slideUp("slow");
console.log(this);
register("subtract", amount, hours);
$(toId(id)).removeAttr("disabled").fadeTo("slow", 1);
$(this).parents(".item").remove();
});
}
問題似乎是click
刪除按鈕時,多次調用了附加到刪除按鈕的click
處理程序。 重復調用register("subtract", amount, hours)
會使總數變為負數。 我怎樣才能解決這個問題?
問題是,每次將商品添加到購物車時,您都要重新運行$(".remove-from-cart").click(...)
,因此所有現有的刪除按鈕都會獲得一個額外的處理程序。
使用jQuery將HTML解析為jQuery包裝的DOM結構,然后將其用作.remove-from-cart
選擇器的上下文(如本工作小提琴所示 )。 這樣, .remove-from-cart
選擇器將僅應用於您新添加的項目。
var selected_product = "<div class=\"item \">" + ...;
// jQuery-wrapped DOM structure
var $prod = $(selected_product)
$prod.insertBefore("#subtotals");
register("add", amount, hours);
// use $prod as jQuery context argument,
// so `.remove-from-cart` only looks in this DOM tree
$(".remove-from-cart", $prod).click(function() {
...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.