【问题标题】:Saving photo on local storage and displaying it on another page将照片保存在本地存储中并在另一个页面上显示
【发布时间】:2023-04-11 12:05:02
【问题描述】:

基本上我有一个带有图像的页面 - 在每个图像下都有一个类似的按钮。当被点赞时,图片应该保存在localStorage上,然后显示在另一个页面上。

HTML 很简单(图像和按钮),如下所示:

        <img data-name="img1" src="photos/photography.jpg" >

        <button type="submit" data-name="img1">Click</button>

这是 jQuery。我正在尝试将喜欢的照片保存在数组中。

         $('button').click((e) => {
             const data = $(e.target).data();
             let arr = $("img");
             const item = arr.filter(v => v.name === data.name)
             let cart = [];
             try {
                 cart = localStorage.getItem('cart');
                 cart = JSON.parse(cart)
             } catch (error) {}
             cart.push(item)
             localStorage.setItem('cart', JSON.stringify(cart));

         })

在带有喜欢图像的页面上,我只是从本地存储中获取项目,但似乎没有任何反应。

如果你能告诉我我做错了什么,我想知道。提前致谢。

【问题讨论】:

  • 你不会对购物车做任何事情,它有块范围顺便说一句......试试没有'let
  • ^^^ 从try 中的cart 中取出let。它正在创建一个在块之外不存在的较低范围的版本。
  • 感谢您的编辑,我删除了它,但它仍然无法正常工作。

标签: javascript jquery html local-storage frontend


【解决方案1】:

您最初的问题是由于在 try catch 中误用了 let。但是,您可以通过将购物车默认为空数组来同时删除 try catch。

$('button').click(e => {
  //get the existing cart, or default to an empty new one
  let cart = JSON.parse( localStorage.getItem('cart') || '[]' );
  //you're only using the name, might as well grab just that
  let itemName = $(e.target).data('name');
  //find the item, same as before
  let item = $('img').filter(v => v.name === itemName);
  
  //add the item to the card
  cart.push(item);
  //put the cart back to storage
  localStorage.setItem('cart', JSON.stringify(cart));
});

【讨论】:

  • 感谢您的回答,但似乎什么也没发生。也许我在仅使用 localStorage.getItem('cart') 获取项目时犯了一个错误?
  • 不,getItem 只需要密钥。
猜你喜欢
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多