基于jQuery Session实现跨页购物车总价留存及NaN问题解决
Hey there! Let's tackle your shopping cart questions with practical, developer-focused solutions.
1. Best way to store shopping cart data
First off, jQuery Session is just a wrapper around either sessionStorage or cookies—it’s not inherently the "best" option, but it depends on your use case. Let’s break down the common storage methods and their pros/cons:
sessionStorage: This is what you’re already testing. It’s great for temporary, per-session storage—data stays until the browser tab/window is closed. It’s client-side only, so no server overhead, and has more storage space than cookies (~5MB vs 4KB). The downside? It doesn’t persist across browser restarts, and data is tied to a single tab (open a new tab, the cart is empty).localStorage: Similar tosessionStorage, but data persists even after the browser is closed. Use this if you want users to come back later and still see their cart items. Just note that it’s still client-side, so sensitive data shouldn’t go here.- Cookies: Older, smaller storage (4KB limit), but data is sent to the server with every request. Useful if you need to sync cart data with your backend, but not ideal for large cart contents.
- Backend Session: If your site has user accounts, storing cart data in your backend’s session (tied to the user’s account or session ID) is the most secure and reliable option. It works across devices, and you can validate/process the server-side before checkout.
So, if you only need temporary cart storage during a single browsing session, sessionStorage is totally fine—no need for jQuery Session specifically, since vanilla JS has native support. If you need persistence across sessions, go with localStorage. For user-specific carts that need to sync with your backend, use server-side sessions.
2. Fixing the NaN & string concatenation issue
The problem here is two-fold:
sessionStoragestores everything as strings, so when you first load the page,sessionStorage.getItem("cartTotal")returnsnull(since nothing’s been stored yet). UsingparseInt(null)gives youNaN, and adding a number toNaNkeeps itNaN.- Without parsing, you’re just concatenating strings (e.g., "15" + 15 = "1515").
Here’s a simple fix to handle both cases—we’ll check if the stored value exists, parse it properly, and default to 0 if it’s empty:
var panel4Price = 15; // Get stored total, parse to integer, default to 0 if null/NaN var cartTotal = parseInt(sessionStorage.getItem("cartTotal"), 10) || 0; $('#addCart').click(function(){ cartTotal += panel4Price; // Now this is numeric addition, not string concat $('#cart').html('£ ' + cartTotal); sessionStorage.setItem("cartTotal", cartTotal.toString()); // Store as string (required for sessionStorage) console.log(cartTotal); });
A few notes on this code:
- We added the second parameter
10toparseInt—this ensures we’re parsing in base 10, avoiding unexpected behavior with numbers starting with 0 (which would otherwise be treated as octal). - The
|| 0takes care of the empty cart case: ifparseIntreturnsNaN(when there’s no stored value), it falls back to 0. - We explicitly convert
cartTotalto a string when storing it back tosessionStorage—though JS will do this automatically, it’s good practice to be clear about it.
If you want even more robust handling (e.g., if someone manually edits the sessionStorage value to a non-number), you can add an extra check:
var storedTotal = sessionStorage.getItem("cartTotal"); var cartTotal = 0; if (storedTotal && !isNaN(parseInt(storedTotal, 10))) { cartTotal = parseInt(storedTotal, 10); }
This way, you ensure you’re only using valid numeric values from storage.
内容的提问来源于stack exchange,提问作者user2669997

