我已經創建了一個基於jQuery的訪客意願清單。基於jQuery的客人願望清單
它具有以下特點:
- 添加項目到列表
- 從清單上的產品數量刪除項目
- 相對時間更新添加
我的問題是,一旦我刷新頁面,所有的項目消失。我確實讀到了解決這個問題的方法是使用localStorage。
由於我創建了一個動態數組,因此我不確定如何將數據存儲和檢索回到面板。
鏈接到我工作的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");
}
}
它似乎是將選擇保存在LS中,但是如何將其顯示回給用戶? – John
不完全確定你的意思是將「that」顯示給用戶。如果要顯示添加到期望列表中的產品,則必須聲明html元素,並在每次調用'localStorage.setItem'後更新它們,並且在'localStorage.getItem'後面第一次調用' – Nosh