我有这个购物车脚本,我正在尝试修改。麻烦的是,每当我尝试从购物车中删除多个商品时,我都会得到负值。删除所有项目后,购物车永远不会回零。我可以添加好的物品。
以下是此功能的代码段。完整的代码是小提琴,因为通过向您展示我遇到的问题的演示更容易解释。
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
处理程序。重复调用register("subtract", amount, hours)
会导致总数变为负数。我该如何解决这个问题?
答案 0 :(得分:2)
问题是每次向购物车添加商品时都会重新运行$(".remove-from-cart").click(...)
,因此所有现有的删除按钮都会获得额外的处理程序。
使用jQuery将HTML解析为jQuery包装的DOM结构,然后将其用作.remove-from-cart
选择器的上下文(如this working fiddle中所示)。这样,.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() {
...
});