2016-11-23 5 views
0

私はカート変数を持っており、この中にカートを格納しています。

[{"course_id":"24","doc_id":"211","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"217","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"218","doc_title":"PDF Solved Past Papers","doc_price":"500"},{"course_id":"26","doc_id":"224","doc_title":"PDF Solved Past Papers","doc_price":"595"}] 

私はRemoveFromCart関数を作成しました。単純なJQUERYで動作しますが、フレームワーク7では$ .grepのために動作しません。 $ .grepを使わないと他の方法ができますか?

これは

function removeFromCart(course_id, doc_id) { 
    var x = confirm("Are you sure you want to remove this item from your cart?"); 
    if (x) { 
     $$('#cart_body').html(''); 
     existing_cart = localStorage.getItem("cart"); 

     if (existing_cart == '') { 
      existing_cart = []; 
     } else { 
      existing_cart = JSON.parse(existing_cart); 
     } 

     existing_cart = $.grep(existing_cart, function (data, index) { 
      return data.doc_id != doc_id 
     }); 

     ex_cart = JSON.stringify(existing_cart); 

     localStorage.setItem('cart', ex_cart); 

     existing_cart = localStorage.getItem("cart"); 

     if (existing_cart == '') { 
      existing_cart = []; 
     } else { 
      existing_cart = JSON.parse(existing_cart); 
     } 
     if (existing_cart !== null && existing_cart.length > 0) { 
      var total = ''; 
      $$('#cart_div').show(); 
      existing_cart.forEach(function (arrayItem) { 
       var text = ''; 
       text = '<li class="item-content"><div class="item-inner"><div class="item-title">' + arrayItem.doc_title + '</div><div class="item-after">' + arrayItem.course_id + '</div><div class="item-after">' + arrayItem.doc_price + '</div><div class="item-after"><i class="icon icon-cross" onclick="removeFromCart(' + arrayItem.course_id + ',' + arrayItem.doc_id + ')"></i></div></div></li>'; 
       total = Number(total) + Number(arrayItem.doc_price); 
       $$('#cart_body').append(text); 
      }); 
      text = '<tr><td></td><td class="text-center"><b>Total: </b></td><td class="text-center">' + total + '</td><td></td></tr>'; 
      $$('#cart_body').append(text); 
     } else { 
      $$('#cart_div').hide(); 
      text = '<p>Your cart is empty.</p>'; 
      $$('#cart_body').append(text); 
     } 
    } else { 
     return false; 
    } 
} 

答えて

3

の代わりに私の機能である:あなたが使用することができます

$.grep(existing_cart, function ... 

existing_cart.filter(function ... 
+0

おはようございます。それはとても簡単でした。 –

0
var new_courses = existing_cart.map(v=> { 
    if(v.doc_id != doc_id) 
    return v 
}).filter(v=> {return v}) 

// new_courses does not contain the course with doc_id 

配列の各メンバーをループmapfilterは、mapで返されていないメンバーを削除します。

関連する問題