我有一些物品,我通過將它們與它們的 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(',') : [];});
如何僅刪除在 localStorage 中多次出現的一個特定數據
臨摹微笑
2023-02-24 16:04:32