亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何僅刪除在 localStorage 中多次出現的一個特定數據

如何僅刪除在 localStorage 中多次出現的一個特定數據

臨摹微笑 2023-02-24 16:04:32
我有一些物品,我通過將它們與它們的 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;

} );

這樣,它只會刪除它遇到的第一個匹配項目。


查看完整回答
反對 回復 2023-02-24
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

你的問題是使用本地存儲,一旦你存儲 ID 數組,它就會以數組的形式存儲,同時檢索你需要獲取字符串 json 解析它的數據,然后運行所需的操作。檢查這個例如



查看完整回答
反對 回復 2023-02-24
  • 2 回答
  • 0 關注
  • 258 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號