2011-12-03 26 views
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(); 
     }); 

    }); 
}); 

非常感謝!

回答

2

我相信你的問題是在這條線:

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

因爲你遍歷項目,但在迭代每個項目不提供一個值,當你調用items.find找到所有的數量值,這意味着當你將它解析爲一個整數時,你總能得到第一個文本。

你可能想是這樣的:

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

+0

謝謝!我認爲這可能有效。我也通過將「項目」改爲「這個」來實現它。 – Peter

0

給誰就給誰第一個回答我的問題,但隨後撤回了答案,謝謝你的提示。它集我嘗試,我得到了它通過更改下面一行在各功能工作:

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

這樣:

var quant = $(this).find('span.qty');