使用localStorage实现购物车:数组仅存最后一个元素的问题求助
Fix: localStorage Only Saves the Last Cart Item
Hey there! I see the issue with your code—let's break it down and fix it quickly.
The Problem
Every time your code runs, you're creating a brand new empty array with let names = []. That means you're not retaining any of the previous items you added; you just push the current item into this fresh array and overwrite the localStorage entry. No wonder only the last item sticks around!
The Solution
You need to first fetch the existing array from localStorage (if there is one), add your new item to that array, then save the updated array back. Here's how to adjust your code:
// Step 1: Get existing items from localStorage, or start with an empty array let names = JSON.parse(localStorage.getItem('name')) || []; // Step 2: Add your new item to the array numPlass++; var set = cart_item.childNodes[numPlass].innerHTML; names.push(set); // Step 3: Save the updated array back to localStorage localStorage.setItem('name', JSON.stringify(names));
Key Notes
- The
JSON.parse(localStorage.getItem('name')) || []part is crucial: if there's nothing stored under the 'name' key (like on first load),getItemreturnsnull, and the|| []ensures we start with an empty array instead of throwing an error. - A quick heads-up:
childNodesincludes text nodes (like spaces or line breaks in your HTML), so you might accidentally grab empty content. If you only want actual element nodes, try usingcart_item.children[numPlass]instead. - To debug, add
console.log(names)after pushing the item—this will show you the full array in your browser's dev tools, so you can confirm multiple items are being added correctly.
内容的提问来源于stack exchange,提问作者שאול שאולי
相关产品推荐
相关产品推荐

