我有一些物品,我通过将它们与它们的 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(',') : [];});
2 回答

开满天机
TA贡献1786条经验 获得超13个赞
永远记住数组方法是你的朋友。array.prototype.find()一种方法是将with的使用结合起来,array.prototype.splice()如下所示:
cartItems.find( ( item, i ) => {
if ( item == this_id ) {
cartItems.splice( i, 1 );
return true;
}
return false;
} );
这样,它只会删除它遇到的第一个匹配项目。

慕的地8271018
TA贡献1796条经验 获得超4个赞
添加回答
举报
0/150
提交
取消