2014-10-18 35 views
0

我有一個簡單的購物車,用戶可以將產品添加到購物車中。每個添加的產品都將作爲一個對象保存到$ .cookie中。

當用戶移除產品時,該產品對象將從Cookie中移除或數量被刪除一個。更新對象數量工作好,我相信。

我的問題是,我不認爲即時使用拼接正確,我無法弄清楚如何使這項工作作爲結果。基本上會發生的情況是,第一個產品對象總是從$ .cookie中刪除,而不是那個具有刪除匹配的特定對象。

下面是我的代碼。我希望有人能夠發現問題。我懷疑這是導致問題的「1」(第一個元素)>> current_objs.splice(current_objs [i],1)

這裏是我的代碼。

$('body').on('click', '.remove_me', function(e) { 

    var productid = $(this).data('productid'); 

    var current_objs = $.cookie("obj"); 

    for (i = 0; i < current_objs.length; i++) { 

    if (current_objs[i].productid === productid.toString()) { 

     if (current_objs[i].qty == 1) { 

     current_objs.splice(current_objs[i],1);   

     $.cookie("obj",current_objs, { path: '/' }); 

     } else { 

     current_objs[i].qty = current_objs[i].qty - 1; 

     $.cookie("obj",current_objs, { path: '/' }); 
     } 

    } 

    } 

}); 

謝謝你提前。

+0

代替'current_objs.splice(current_objs [I],1); 'try'current_objs.splice(i,1); '。 – 2014-10-18 00:23:38

回答

0

的JavaScript array.splice()具有以下參數:

array.splice(index, howMany, item1, item2, .., itemN) 

  • index是在陣列的索引添加/刪除的項目。
  • howMany是要移除的元素的數量。
  • item1-N是要添加的項目。

嘗試此代替:

current_objs.splice(i, 1); // remove 1 item and index i