我的表下方显示未定义 - 会话存储



下面的代码有效,但问题是未定义显示在我的表下方。我试图删除sessionStorage.basket === undefined,但它删除了整个表。有人可以帮助我吗?

// Load basket on page
window.onload = loadBasket;
// Displays basket in page.
function loadBasket() {
// Get basket from local storage or create one if it does not exist
var basketArray;
if(sessionStorage.basket === undefined || sessionStorage.basket === "") {
// Store as an array
basketArray = [];
}
else {
// Parse the data as an object
basketArray = JSON.parse(sessionStorage.basket);
}
// Build string with basket HTML
var htmlStr = "<form action='php/checkout.php' method='post'>";
// Get table body
var tableBody;
// Display table headers
var tableHeader = "<tr><th>Product Image</th><th>Product Name</th><th>Price</th></tr>n";
// Store IDs as array
var prodIDs = [];
// For loop to display more products on the table
for(var i=0; i<basketArray.length; ++i) {
tableBody += "<tr><td class='image_column'>" + "<img class='basket_img' src='" + basketArray[i].image + "'>" + "</td><td>" + basketArray[i].name + "</td><td>£" + basketArray[i].price + "</td></tr>";
// Push data to insert into the database
prodIDs.push({
image: basketArray[i].image, 
name: basketArray[i].name, 
price: basketArray[i].price, 
count: 1
});
}
// Add hidden field to form that contains stringified version of product ids.
htmlStr += "<input type='hidden' name='prodIDs' value='" + JSON.stringify(prodIDs) + "'>"; 
// Display the number of items in the basket
htmlStr += "<p class='basket_items'>Number of items in basket: " + "<span style='color:red'>" + basketArray.length + "</span>" + "</p>"; 
// Add checkout and empty basket buttons
htmlStr += "<button class='empty_basket' onclick='emptyBasket()'>Empty Basket</button>";
htmlStr += "<input class='checkout_button' type='submit' value='Checkout'></form>";
// Display number of products in basket
document.getElementById("basketDiv").innerHTML = htmlStr;
// Display table
document.getElementById("basket_list").innerHTML = tableHeader + tableBody;
}

在没有特定使用理由之前,使用localStorage而不是sessionStorage

原因: 每个窗口都可用sessionStorage,并且您可能在其他窗口上存储了购物篮的价值并尝试进入不同的窗口。

localStorage而不是sessionStorage之间的区别:

本地存储

存储在localStorage中的数据将一直存在,直到明确删除。所做的更改将被保存,并可用于当前和将来对网站的所有访问。

会话存储

对于sessionStorage,更改仅按窗口(或Chrome和Firefox等浏览器中的选项卡)可用。所做的更改将被保存并可用于当前页面,以及将来在同一窗口中访问该网站。关闭窗口后,将删除存储。

您的问题

首先,请确保正确设置localStorage中的值(对象数组)。这样做:

localStorage.setItem("basket", JSON.stringify(basketvalues));

现在,函数loadBasket()条件将如下所示:

if(localStorage.getItem("basket") === undefined || localStorage.getItem("basket") === "") {
// Store as an array
basketArray = [];
}
else {
// Parse the data as an object
basketArray = JSON.parse(localStorage.getItem("basket"));
}

有关本地存储的更多信息,请阅读此链接:

https://www.w3schools.com/jsref/prop_win_localstorage.asp

最新更新