How to build a basic shopping cart with HTML5 sessionStorage.
首先使用HTML创建商品列表,每个商品包含名称、价格和“添加到购物车”按钮。通过JavaScript的sessionStorage将商品数据以字符串化JSON格式存储,实现页面刷新后数据仍保留。定义addToCart函数向购物车添加商品,内部获取或初始化购物车数组,追加新商品并更新sessionStorage。每次操作后调用updateCart函数,该函数从sessionStorage读取数据并动态生成购物车列表,同时计算总价并更新页面显示。设置clearCart函数用于清空购物车,并在页面加载时调用updateCart恢复购物车状态,确保用户体验连续性。整个方案基于前端技术,无需服务器支持,利用sessionStorage实现会话级数据持久化,关闭浏览器后数据自动清除。

To build a basic shopping cart using HTML5 sessionStorage, you can store product data as a stringified JSON object. This allows items to persist during the browsing session, even if the page is refreshed. Here's how to set it up simply and effectively.
Create the Product List (HTML)
Start with a simple list of products. Each item needs a name, price, and an "Add to Cart" button.
<div class="product">
<span>T-Shirt - $20</span>
<button onclick="addToCart('T-Shirt', 20)">Add to Cart</button>
</div>
<p><div class="product">
<span>Jeans - $50</span>
<button onclick="addToCart('Jeans', 50)">Add to Cart</button>
</div></p>Manage Cart with JavaScript
Use JavaScript functions to add items, update the cart display, and save data in sessionStorage.
// Add item to cart
function addToCart(name, price) {
let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
cart.push({ name, price });
sessionStorage.setItem("cart", JSON.stringify(cart));
updateCart();
}
<p>// Display cart items
function updateCart() {
const cart = JSON.parse(sessionStorage.getItem("cart")) || [];
const cartContainer = document.getElementById("cart-items");
const totalElement = document.getElementById("total");</p><p>cartContainer.innerHTML = ""; // Clear current display</p><p>let total = 0;
cart.forEach(item => {
total += item.price;
const li = document.createElement("li");
li.textContent = <code>${item.name} - $${item.price}</code>;
cartContainer.appendChild(li);
});</p><p>totalElement.textContent = total;
}</p>Show the Shopping Cart
Add a section to display the selected items and total cost.
<h2>Your Cart</h2> <ul id="cart-items"></ul> <p>Total: $<span id="total">0</span></p> <button onclick="clearCart()">Clear Cart</button>
You can also include a function to clear the cart:
function clearCart() {
sessionStorage.removeItem("cart");
updateCart();
}
Call updateCart() when the page loads to restore the cart from storage:
window.onload = updateCart;
That’s it. You now have a working session-based shopping cart. The data stays only for the current session and clears when the browser closes. No backend needed—just plain HTML, CSS, and JavaScript using sessionStorage. Basically just store, retrieve, and sync the UI.
The above is the detailed content of How to build a basic shopping cart with HTML5 sessionStorage.. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4




