我有一些物品,我通过将它们与它们的 ID 一起存储在 localStorage 中来添加到购物车。
$(document).on('click', '.set-cart-info', function () {
// We retrieve the product id which is stored in the url
var url_id = window.location.search;
var id = url_id.split('?id=').pop();
// We retrieve the data from the localStorage
var cartItems = localStorage.getItem('teddy_id');
// If there is no data, we create an array
cartItems = cartItems ? cartItems.split(',') : [];
// Add the new data to the array
cartItems.push(id);
// We save the data in the localStorage
localStorage.setItem('teddy_id', cartItems.toString());
});
在 console.log 我得到这个:
localStorage.getItem('teddy_id')
"5beaacd41c9d440000a57d97,5beaabe91c9d440000a57d96,5beaabe91c9d440000a57d96,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaacd41c9d440000a57d97,5beaaa8f1c9d440000a57d95,5beaaa8f1c9d440000a57d95,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaaa8f1c9d440000a57d95"
然后,我添加了通过检索产品 ID 并将其添加到 localStorage 来添加或删除产品数量的可能性,我的问题如下:当我检索 ID 以在 localStorage 中获取它时,它会删除所有项目这个 ID,我希望它只删除一个。
这是允许添加数量的代码,以及应该修改的代码,以便它也只删除一个:
$(document).on('click', '.add_qty', function () {
// We retrieve the product id which is stored in the class
var split_class = this.className.split(' ');
var this_id = split_class[1];
var cartItems = localStorage.getItem('teddy_id');
cartItems = cartItems ? cartItems.split(',') : [];
cartItems.push(this_id);
localStorage.setItem('teddy_id', cartItems.toString());
});
$(document).on('click', '.remove_qty', function () {
// We retrieve the product id which is stored in the class
var split_class = this.className.split(' ');
var this_id = split_class[1];
var cartItems = localStorage.getItem('teddy_id');
cartItems = cartItems ? cartItems.split(',') : [];
});
开满天机
慕的地8271018
相关分类