JS新手大学作业问题:Cookie与SessionStorage无法存储用户名
Hey there! Let's work through this step by step since you're new to JavaScript—no worries, we'll get your shopping list app working as expected 😊
1. Why Your Cookie Isn't Saving Correctly
The main issue with your cookie code is that you didn't format it properly. Cookies require a key=value structure, but you just set document.cookie = name_input;—this doesn't give the cookie a name, so the browser doesn't store it correctly.
For a session-level cookie (which expires when the browser closes), you just need to define a key (like username) and encode the value to handle special characters (spaces, symbols, etc.):
document.cookie = `username=${encodeURIComponent(name_input)}`;
2. SessionStorage Was Also Misused
Your sessionStorage.setItem(name_input); call is missing a critical parameter: the key name. SessionStorage uses key-value pairs, so you need to pass both a key (to reference the value later) and the value itself:
sessionStorage.setItem("username", name_input);
3. Variable Scope & Logic Flaws
You declared var name_input inside the if (!name_input) block, which causes scope issues—later checks for name_input != null might not work as expected. Also, your initial logic doesn't check if a username is already stored in sessionStorage or cookies (which is required for your task!).
We need to:
- First check if a username exists in sessionStorage
- If not, check cookies for an existing username
- Only prompt the user if neither has a stored value
4. Full Fixed Code
Here's the revised code with all fixes, plus comments explaining each change:
<!DOCTYPE html> <html> <head> <title id="g"></title> <script> // Helper function to get a specific cookie by name function getCookie(name) { // Split cookie string and get all individual key-value pairs const cookies = document.cookie.split(';').map(cookie => cookie.trim()); for (const cookie of cookies) { if (cookie.startsWith(`${name}=`)) { // Extract and decode the value return decodeURIComponent(cookie.substring(name.length + 1)); } } return null; // Return null if cookie doesn't exist } function name_inp() { // First check sessionStorage for existing username let username = sessionStorage.getItem("username"); // If no sessionStorage value, check cookies if (!username) { username = getCookie("username"); } // If neither has a username, prompt the user if (!username) { username = prompt("Please enter your name"); // Only store if user didn't cancel the prompt if (username) { // Save to sessionStorage sessionStorage.setItem("username", username); // Save to session-level cookie (no expires = session-only) document.cookie = `username=${encodeURIComponent(username)}`; } } // Update the page title/heading if we have a username if (username) { const headingText = `${username}'s Shopping List`; document.getElementById("g").innerHTML = headingText; document.title = headingText; // Also update the browser tab title! } } </script> </head> <body style="text-align: center;" onload="name_inp()"> <h1 id="g"></h1> <form action="index.html" method="post"> <label>Product 1</label><br> <input type="text" id="1stprod"><br> <label>Amount</label><br> <input type="number" id="1stnum"><br> <label>Product 2</label><br> <input type="text" id="2ndprod"><br> <label>Amount</label><br> <input type="number" id="2ndnum"><br> <label>Product 3</label><br> <input type="text" id="3rdprod"><br> <label>Amount</label><br> <input type="number" id="3rdnum"><br> <input type="submit"> </form> </body> </html>
Key Changes Explained:
- Added a
getCookiehelper function to safely retrieve cookies by name - Fixed sessionStorage and cookie storage to use proper key-value pairs
- Rearranged logic to prioritize stored values before prompting the user
- Added encoding/decoding for cookies to handle special characters
- Fixed variable scope by declaring
usernameat the top of the function - Updated both the page heading and browser tab title to match your requirement
内容的提问来源于stack exchange,提问作者Александр Трохачев

