限制可添加到购物车的商品数量 - simpleCart

时间:2014-10-22 08:37:30

标签: jquery simplecart

尝试将允许添加的项目总数限制为4,此功能首次提醒,但仍会将项目添加到购物车。

simpleCart.bind( 'beforeAdd' , function( item ){

        if(simpleCart.quantity() === 4 ){

             alert("You can only compare 4 items."); 
             return false;

        }

   });

2 个答案:

答案 0 :(得分:0)

它只检查添加的第4个元素并继续添加元素。如果您要检查数量是否等于或大于4,以防止添加更多项目:)

simpleCart.bind( 'beforeAdd' , function( item ){

    if(simpleCart.quantity() >= 4 ){

         alert("You can only compare 4 items."); 
         return false;

    }

});

答案 1 :(得分:0)

SimpleCart(v3)将项目传递给beforeAdd,该项目仅代表要添加到购物车的商品和数量。代码需要考虑购物车中已有的任何商品。

simpleCart.bind('beforeAdd', function (item) {
    var requestedQuantity = item.get('quantity');
    var existingItem = simpleCart.has(item);
    if (existingItem) {
        requestedQuantity += existingItem.get('quantity');
    }
    if (requestedQuantity > 4) {
        alert("You may compare at most 4 items.");
        return false;
    }
});
相关问题