簡體   English   中英

將照片保存在本地存儲中並在另一頁上顯示

[英]Saving photo on local storage and displaying it on another page

基本上,我的頁面上有圖片-在每個圖片下都有一個按鈕。 當喜歡時,圖像應保存在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));

         })

在帶有喜歡圖像的頁面上,我只是從本地存儲中獲取項目,但似乎什么也沒有發生。

我想告訴你我在做什么錯。 提前致謝。

您的原始問題是由於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)); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM