如何在JavaScript/HTML中存储用户输入的事件信息并支持多次添加
First, let's fix the immediate issue in your original code: your two input elements share the same id and name values ("name"), which breaks HTML rules (IDs must be unique) and makes it impossible to correctly fetch each input's value. Let's rewrite the base HTML with proper identifiers, plus add a submit button and a container to display events:
<!-- Fixed Inputs & Form --> <form id="eventForm"> <label for="eventlocation">Event Location (1 to 20 characters):</label> <input type="text" id="eventlocation" name="eventlocation" required minlength="1" maxlength="20" size="20"> <label for="datetime">Event Date and Time:</label> <input type="datetime-local" id="datetime" name="datetime" required> <button type="submit">Add Event</button> </form> <!-- Container to Display Saved Events --> <div id="eventList"> <h3>Your Upcoming Events:</h3> </div>
Next, we'll use JavaScript to handle form submission, store events (using localStorage for persistent storage across page reloads), and render the event list dynamically. Here's the full script:
// Wait for the page to load before running code document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('eventForm'); const eventList = document.getElementById('eventList'); // Load existing events from localStorage when the page loads renderEvents(); // Handle form submission form.addEventListener('submit', (e) => { e.preventDefault(); // Stop the form from reloading the page // Get input values const location = document.getElementById('eventlocation').value.trim(); const dateTime = document.getElementById('datetime').value; // Create an event object with a unique ID const event = { id: Date.now().toString(), // Unique ID using timestamp location: location, dateTime: dateTime }; // Save event to localStorage saveEvent(event); // Clear form inputs for next entry form.reset(); // Re-render the event list to show the new event renderEvents(); }); // Function to save event to localStorage function saveEvent(event) { // Get existing events (or empty array if none exist) const events = JSON.parse(localStorage.getItem('events')) || []; // Add new event to the array events.push(event); // Save updated array back to localStorage localStorage.setItem('events', JSON.stringify(events)); } // Function to render events to the page function renderEvents() { // Clear existing list to avoid duplicate entries eventList.innerHTML = '<h3>Your Upcoming Events:</h3>'; const events = JSON.parse(localStorage.getItem('events')) || []; if (events.length === 0) { eventList.innerHTML += '<p>No events added yet.</p>'; return; } // Create a list to hold events const ul = document.createElement('ul'); events.forEach(event => { const li = document.createElement('li'); // Format date/time for better readability const formattedDate = new Date(event.dateTime).toLocaleString(); li.innerHTML = ` <strong>${event.location}</strong> - ${formattedDate} <button onclick="deleteEvent('${event.id}')">Delete</button> `; ul.appendChild(li); }); eventList.appendChild(ul); } // Function to delete an event window.deleteEvent = function(eventId) { let events = JSON.parse(localStorage.getItem('events')) || []; // Filter out the event with the matching ID events = events.filter(event => event.id !== eventId); // Save updated array back to localStorage localStorage.setItem('events', JSON.stringify(events)); // Re-render the list to reflect changes renderEvents(); }; });
Key Features Explained:
- Fixed Input Identifiers: Updated your
id/nameattributes to be unique, so we can reliably fetch each input's value. - Persistent Storage: Uses
localStorageto save events, so they'll remain even if the user refreshes the page or closes the browser. - Dynamic Rendering: The
renderEvents()function updates the event list every time a new event is added or deleted. - Delete Functionality: Added a delete button for each event to let users remove unwanted entries.
- Input Validation: Retained your original
required,minlength, andmaxlengthattributes to ensure valid user input.
If you don't need persistent storage (i.e., events can disappear when the page reloads), you can replace the localStorage logic with a simple in-memory array: just declare let events = []; at the top of the script, and remove all references to localStorage.getItem and localStorage.setItem.
内容的提问来源于stack exchange,提问作者Lachlan D

