Javascript:从购物车中减去项目会导致负值

Javascript: Subtracting items from shopping cart result in negative value

本文关键字:项目 购物车 Javascript      更新时间:2023-09-26

我有一个购物车脚本,正在尝试修改。问题是,每当我试图从购物车中删除多个项目时,我都会得到一个负值。删除所有项目后,购物车永远不会归零。我可以很好地添加项目。

这是小提琴。

以下是此功能的代码片段。完整的代码是在小提琴,因为它更容易解释,通过向你展示我遇到的问题的演示。

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)的重复调用导致总数为负数。我该怎么解决这个问题?

问题是,每次向购物车添加项目时,都会重新运行$(".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() {    
    ...
});