简体   繁体   中英

Jquery and php wishlist - how to retrieve data?

I have a script that randomly shows divs when you press a button. I would like to make a wish list page in order for people to keep track of what they liked. I have set a session and a cookie for a day. this is my script and it doesn't work but I'm not sure why... Thanks for all your help.

$(".places").hide();

$("#button").click(function(){
    "use strict";
     var randomNumber = Math.floor(Math.random()*45);
     var selectedDiv = "#place" + randomNumber;
     $('.places').hide().filter(selectedDiv).show();
     $(".wishlistbutton").click(localStorage.setItem(selectedDiv,JSON.stringify(wishlist)));
});

var wishlistkey = "wishlist";
var wishlist = localStorage.getItem(wishlistkey);

if($.isEmptyObject(wishlist)){
    wishlist = new Array()
} else {
    wishlist = JSON.parse(wishlist);
}

The $.isEmptyObject method does not work as you expected since you are providing a string as the argument(expected argument type is a plain JS object), actually which is unnecessary in your code.

var wishlist = localStorage.getItem(wishlistkey);
if(!wishlist){
   wishlist = new Array()}
else {
   wishlist = JSON.parse(wishlist);
}

Although you need to store the JSON string in localStorage with key as wishlist instead of the div id.

localStorage.setItem('wishlist', JSON.stringify(wishlist))

看起来您正在调用localStorage setItem并传入一个键,它是div的名称(selectedDiv),但是随后您试图在名为“ wishlist”的键上获取Item尝试在存储中设置此项

$(".wishlistbutton").click(localStorage.setItem("wishlist", JSON.stringify(wishlist))); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM