You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从sessionStorage获取对象?解决购物车数据存储异常问题

Fixing Your SessionStorage Cart Issue

Let's break down what's going wrong here and fix it step by step:

What's Causing the Problem?

  1. Overwriting the Same SessionStorage Key: Every time you click an "add" button, you're calling sessionStorage.setItem("cart", JSON.stringify(element)) — this replaces the entire "cart" entry with just the current dish. That's why only the last added item shows up, and others get lost.
  2. Mixing Up localStorage and sessionStorage: In your RetrieveDataFromCart function, you used localStorage.key(i) instead of sessionStorage.key(i), which means you're trying to read from the wrong storage entirely.
  3. Inefficient Event Binding: Binding click events inside a loop for dynamically created elements works here (since you used let), but event delegation is a cleaner, more scalable approach.

The Fix: Store Cart as an Array

Instead of storing single items under the same key, we'll store an array of cart items in sessionStorage. Here's the revised code:

Updated JavaScript

const foodList = [{ 
  id: 1, name: "Spaghetti", price: 15, category: "main", pictureSrc: "images/food/spaghetti.jpg" 
}, { 
  id: 2, name: "Lasagne", price: 20, category: "main", pictureSrc: "images/food/Lasagne.jpg" 
}, { 
  id: 3, name: "Coca-cola", price: 5, category: "drinks", pictureSrc: "images/food/cola.jpg" 
}, { 
  id: 4, name: "Chicken", price: 12, category: "main", pictureSrc: "images/food/chicken.jpg" 
}];

function InitializeFoodList() {
  const $foodList = $('#foodList');
  $foodList.empty(); // Clear existing items if re-running the function

  // Build the food list HTML
  foodList.forEach((item, index) => {
    const buttonHtml = `
      <button class="btn btn-primary add" data-item-id="${item.id}">+</button>
      <button class="btn btn-primary remove" data-item-id="${item.id}">-</button>
    `;
    const listItemHtml = `
      <li class='list-inline-item'>
        <h4>${item.name}</h4>
        <p>${item.price} zł</p>
        <img alt="${item.name}" height='200' width='200' class='img-thumbnail' src='${item.pictureSrc}'>
        <br>${buttonHtml}
      </li>
    `;
    $foodList.append(listItemHtml);
  });

  // Use event delegation for add/remove buttons (works for dynamic elements)
  $foodList.on('click', '.add', function() {
    const itemId = parseInt($(this).data('item-id'));
    const selectedItem = foodList.find(item => item.id === itemId);
    
    // Get existing cart from sessionStorage, or initialize empty array
    let cart = JSON.parse(sessionStorage.getItem('cart')) || [];
    
    // Optional: Prevent duplicate items (uncomment if needed)
    // const existingItem = cart.find(item => item.id === itemId);
    // if (!existingItem) {
    //   cart.push(selectedItem);
    // }
    
    // Push the new item and save back to sessionStorage
    cart.push(selectedItem);
    sessionStorage.setItem('cart', JSON.stringify(cart));
  });

  // Optional: Add remove functionality
  $foodList.on('click', '.remove', function() {
    const itemId = parseInt($(this).data('item-id'));
    let cart = JSON.parse(sessionStorage.getItem('cart')) || [];
    cart = cart.filter(item => item.id !== itemId);
    sessionStorage.setItem('cart', JSON.stringify(cart));
  });
}

function RetrieveDataFromCart() {
  // Get the entire cart array from sessionStorage
  const cart = JSON.parse(sessionStorage.getItem('cart')) || [];
  
  if (cart.length === 0) {
    console.log('Cart is empty!');
    return;
  }
  
  console.log('Cart items:');
  cart.forEach(item => {
    console.log(`- ${item.name} (${item.price} zł)`);
  });
}

Updated HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button onclick="InitializeFoodList()">Load Food List</button>
  <button onclick="RetrieveDataFromCart()">Show Cart in Console</button>
  <ul id="foodList" class="list-inline"></ul>
</div>

Key Improvements:

  • Stores Cart as an Array: We now read the existing cart array, add new items to it, and save the updated array back to sessionStorage — no more overwriting!
  • Event Delegation: Instead of binding events to each button individually, we listen for clicks on the parent #foodList element. This works even if you dynamically add more items later.
  • Data Attributes: We use data-item-id to link buttons to their corresponding food items, making the code more maintainable than relying on button IDs like add1.
  • Optional Remove Functionality: Added a basic remove feature to complement the add button.
  • Safety Checks: We use || [] to handle cases where the cart doesn't exist in sessionStorage yet (initial load).

Bonus: Preventing Duplicate Items

If you don't want users to add the same dish multiple times, uncomment the "Prevent duplicate items" section in the add button click handler. This checks if the item is already in the cart before adding it.

内容的提问来源于stack exchange,提问作者cannelle28

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:13:35