1

我是新手,使用购物车示例在 jquery 上编写和完成本教程:http: //jumpstartlab.com/resources/jquery-jumpstart/jscart---a-jquery-shopping-cart/

当我尝试合计购物车中的数量时遇到了麻烦。总数是一些奇怪的数字,比如库存数量的倍数。如果有人有任何想法可以帮助我解决我的错误,我将不胜感激。这是有问题的部分:

var JSCart = {
  update_cart_item_count : function () {
    var items = $('#cart div.cart_item');
    var total = 0;

    items.each(function (){

        var quant = items.find('span.qty');
        var value = parseInt(quant.text());        
        total = total + value;
        $('span#cart_quantity').text(total);
        });
},

这是整个事情,包括该部分:

$(document).ready(function (){

var inventory = $(raw_inventory); 

var prototype_item = $('#prototype_item');
prototype_item.detach();    

var prototype_cart = $('#prototype_cart');
prototype_cart.detach();  

var JSCart = {
    update_cart_item_count : function () {
        var items = $('#cart div.cart_item');
        var total = 0;

        items.each(function (){

            var quant = items.find('span.qty');
            var value = parseInt(quant.text());        
            total = total + value;
            $('span#cart_quantity').text(total);
            });
    },
    update_cart_total : function () {   
    },
    update_cart : function () {
         this.update_cart_item_count();
         this.update_cart_total();
         //alert('Updating the cart...');
         }
    };

 inventory.each(function(){
  //     alert("Inserting " + this.name);
       var item = prototype_item.clone();  
            item.find('h3').text(this.name);
            item.find('span.price').text(this.price);
            item.find('span.qty').text(this.stock);
            $('div#prototype_item').attr('id', 'product_' + this.product_id);
            $('#inventory').append(item);

       var cart_item = prototype_cart.clone();
            cart_item.find('h3').text(this.name);              
            $('div#prototype_cart').attr('id', 'product_' + this.product_id);
            $('#cart').append(cart_item);

       item.click(function () {
        //alert("Adding " + $(this).attr('id') + " to the cart." );
            var target_id = $(this).attr('id'); 
            var target = $('div#cart div#' + target_id); 

            var quantity = target.find('span.qty'); 
            var current = parseInt(quantity.text()); 
            $(quantity).text(current + 1); 
            JSCart.update_cart();
        });

  });
});

非常感谢!

4

2 回答 2

2

我相信您的问题出在这一行:

var quant = items.find('span.qty');

因为您正在迭代项目,但在调用items.find它时没有为迭代中的每个项目提供值会找到所有 qty 值,这意味着当您将第一个项目解析为整数。

你可能想要这样的东西:

$('div.cart_item').each(function (i, item) {})

于 2011-12-03T05:54:34.833 回答
0

谁先回答了我的问题,然后又撤回了答案,谢谢您的提示。它让我开始试验,我通过更改每个函数中的以下行来让它工作:

 var quant = items.find('span.qty');

对此:

var quant = $(this).find('span.qty');
于 2011-12-04T00:45:23.203 回答