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すべての数量値が検出されます。つまり、最初のアイテムのテキストを解析するときに常に取得されます。整数。

あなたはおそらくこのようなものが欲しいでしょう:

$('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 に答える