简体   繁体   English

基于jQuery的访客愿望清单

[英]jQuery based Guest Wishlist

I have created a jQuery based guest wish list. 我创建了一个基于jQuery的客户愿望清单。

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. 我确实读过,克服此问题的方法是使用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: 可以在这里找到到我正在工作的JSFiddle的链接: https ://jsfiddle.net/ypujmpnj/ jQuery代码附在下面:

 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/ 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. 简短的答案:localStorage仅处理字符串,因此您需要使用JSON.stringify和JSON.parse来存储和加载数组。

Long answer: You need to start by replacing your declaration var wish_list = new Array(); 长答案:您需要首先替换声明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. 您在这里正在寻找的东西可能以前已经保存在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. 下一步:每次修改wish_list时,都必须保存它。 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: 所以,做了之后wish_list.push在添加单击处理程序,并经过wish_list = $.grep( ...在remove单击处理线,必须将其写入使用以下行相同的localStorage的关键:

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

This will have to be done wherever and whenever you update the wish_list array. 无论何时何地,只要您更新wish_list数组,都必须这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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