简体   繁体   中英

jQuery based Guest Wishlist

I have created a jQuery based guest wish list.

It has the following features:

  1. Add item to the list
  2. Remove item from the list
  3. Rel time update on amount of products added

My problem is that once I refresh the page all of the items disappear. I did read that the way to overcome this is to use localStorage.

Due to the fact that I create a dynamic array I am not sure how I can store and retrieve the data back into the panel.

Link to my working JSFiddle can be found here: https://jsfiddle.net/ypujmpnj/ The jQuery code is attached below:

 var wish_list = new Array(); $(document).ready(function() { $(".wishlist").on("click", function() { $data = ""; $product_id = $(this).attr("product_id"); a $product_name = $(this).attr("product_name"); $prduct_price = $(this).attr("product_price"); //check if the element is in the array if ($.inArray($product_id, wish_list) == -1) { $product_str = "<tr class='wishlist-item' id='list_id_" + $product_id + "'><td class='w-pname'>" + $product_name + "</td><td class='w-price'>$ " + $prduct_price + "</td><td class='w-premove' wpid='" + $product_id + "'>x</td></tr>"; $("#wish_list_item").append($product_str); wish_list.push($product_str); show_message("Product " + $product_name + " added"); count_items_in_wishlist_update(); } }); //adding toggle functionality to the wishlist pannel $(".wish_list_heading").on("click", function() { if (!$(this).hasClass("up")) { $("#wish_list").css("height", "300px"); $(this).addClass("up"); $("#wish_list").css("overflow", "auto"); } else { $("#wish_list").css("height", "30px"); $(this).removeClass("up"); $("#wish_list").css("overflow", "hidden"); } }); $("#wish_list_item").on("click", ".w-premove", function() { $product_id = $(this).attr("wpid"); $("#list_id_" + $product_id).remove(); wish_list = $.grep(wish_list, function(n, i) { return n != $product_id; }); show_message("Product removed"); count_items_in_wishlist_update(); }); }); function show_message($msg) { $("#msg").html($msg); $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px"; $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px"; $("#msg").css("left", $left); $("#msg").animate({ opacity: 0.6, top: $top }, 400, function() { $(this).css({ 'opacity': 1 }); }).show(); setTimeout(function() { $("#msg").animate({ opacity: 0.6, top: "0px" }, 400, function() { $(this).hide(); }); }, 1000); } //Validation against the amount of product being added function count_items_in_wishlist_update() { $("#listitem").html(wish_list.length); if (wish_list.length > 1) { $("#p_label").html("Products"); } else { $("#p_label").html("Product"); } } 

You can define a few helper functions like one for storing the updated wishlist in local storage each time an item is clicked and also a function to load the wish_list when page is refreshed and similarily for removing from storage.

Here's your updated fiddle showing items not removed after page refresh. https://jsfiddle.net/ypujmpnj/37/

function pushToStorage(arr) {
  if (typeof(Storage) !== "undefined") {
    localStorage.clear();
    localStorage.setItem("wish_list", JSON.stringify(arr));
    var stored_wishList = JSON.parse(localStorage.getItem("wish_list"));
  } else {
    console.log("your browser does not support Storage");
  }
}

function loadExisting() {
  var stored_wishList = JSON.parse(localStorage.getItem("wish_list"));
  if (stored_wishList != null) {
    wish_list = stored_wishList;

    stored_wishList.forEach(function(item, index, arr) {
      console.log(item);
      $("#wish_list_item").append(item);
    });
    count_items_in_wishlist_update();
  }
}

            $(document).ready(function() {
            loadExisting();
            $(".wishlist").on("click", function() {
                pushToStorage(wish_list);
            });
            })

Short answer: localStorage only deals with strings so you'll need to use JSON.stringify and JSON.parse to store and load your array.

Long answer: You need to start by replacing your declaration var wish_list = new Array(); with the following block:

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = localStorage.getItem(wishlistkey)
if($.isEmptyObject(wish_list)) //nothing was saved previously
  wish_list = new Array()
else // this is the case where something was previously saved.
  wish_list = JSON.parse(wish_list)

What you're doing here is looking for an item that may have been previously saved in the localStorage. If it is found, you try and parse it. If not, you create a new array.

Next: every time you modify the wish_list, you must save it. So, after doing a wish_list.push in the add click handler, and after the wish_list = $.grep( ... line in the remove click handler, you must write it to the same localStorage key using the following line:

localStorage.setItem(wishlistkey, JSON.stringify(wish_list))

This will have to be done wherever and whenever you update the wish_list array.

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