[英]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') );
});
有幾處錯誤:
product_ids
始終為空,因為您需要push()
或unshift()
或任何東西來填充數組。 localStorage
只能接受字符串,我什至認為它甚至都不會識別您的空數組。 localStorage
push()
放入數組productList
。 productList
更新時,它都存儲在隱藏的輸入#cache
#cache
被轉換成一個字符串JSON.stringify
。 productList
是字符串,則將其存儲在localStorage
並顯示在#output
。 由於存在沙箱,因此該代碼段無法正常工作,因此請查看此PLUNKER 。
<!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.