簡體   English   中英

添加本地存儲數組

[英]Adding localstorage array

我在使用此localstorage陣列時遇到了困難。 我已經在這里搜索到了,但是找不到。 希望你能幫我這個忙。

這是我的代碼。

$(function(){
    var addWishlist = $('.add-wishlist');
    addWishlist.click(function(e){
        e.preventDefault();
        var product_ids = [];
        localStorage.setItem('product_ids', $(this).prev().val() );
        console.log( localStorage.getItem('product_ids') );
    });
});

輸出為: 在此處輸入圖片說明

輸出應為[2、3、4、1]

您需要在單擊按鈕時將其添加到數組,然后將其存儲到本地存儲。 同樣, product_ids應該在click事件之外初始化

var product_ids = [];
addWishlist.click(function(e){
        e.preventDefault();      
        product_ids.push($(this).prev().val())
        localStorage.setItem('product_ids',product_ids );
        console.log(localStorage.getItem('product_ids') );
    });

有幾處錯誤:

  1. 數組product_ids始終為空,因為您需要push()unshift()或任何東西來填充數組。
  2. localStorage只能接受字符串,我什至認為它甚至都不會識別您的空數組。

變化

  1. 添加了一個額外的按鈕以將數據加載到localStorage
  2. 輸入文本,然后單擊添加按鈕。
  3. 文本輸入的值被push()放入數組productList
  4. 每次productList更新時,它都存儲在隱藏的輸入#cache
  5. 當點擊完成按鈕,的值#cache被轉換成一個字符串JSON.stringify
  6. 一旦productList是字符串,則將其存儲在localStorage並顯示在#output

由於存在沙箱,因此該代碼段無法正常工作,因此請查看此PLUNKER

SNIPPET

 <!DOCTYPE html> <html> <head> </head> <body> <fieldset> <legend>wishList</legend> <input id='in1'> <button><a href='#' id='add'>Add</a> </button> <button><a href='#' id='done'>Done</a> </button> <label for='out1'>wishList:</label> <output id='out1'></output> <input id='cache' type='hidden'> </fieldset> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(function() { var productList = []; $('#add').on('click', function(e) { e.preventDefault(); var productItem = $('#in1').val(); productList.push(productItem); $('#cache').val(productList); }); $('#done').on('click', function(e) { e.preventDefault(); var cached = $('#cache').val(); var str = JSON.stringify(cached); localStorage.setItem('proList', str); var stored = localStorage.getItem('proList'); console.log(stored) $('#out1').html(stored); }); }); </script> </body> </html> 

暫無
暫無

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

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