DOM加载后用jQuery .each遍历多元素,将表单值存入多维数组
Collecting Person Data into a Multidimensional Array with jQuery
Got it, let's walk through how to grab all that person data into a neat array once the DOM's fully loaded. Here's a step-by-step solution tailored to your setup:
Step 1: Wait for the DOM to Load
First, wrap everything in jQuery's DOM ready handler to make sure all elements exist before we try to access them:
$(document).ready(function() { // Our data collection code goes here });
Step 2: Iterate Over Each Person Entry
We'll target each <li> with the class showperson inside the #person list. For each entry, we'll extract values from your input, datepicker, image, and bio elements:
$(document).ready(function() { // Initialize an empty array to store all person data const peopleData = []; // Loop through each person's list item $('#person li.showperson').each(function(index, element) { const $person = $(element); // Extract values from elements inside this person's entry // Adjust these selectors to match your actual HTML IDs/classes/names const personInfo = { fullName: $person.find('input[name="full-name"]').val(), birthDate: $person.find('.datepicker').val(), profileImage: $person.find('img.profile-pic').attr('src'), bio: $person.find('.bio-text').val() // Use .text() if it's a static div instead of a textarea }; // Add this person's data to the main array peopleData.push(personInfo); }); // Now you can use the peopleData array for submission, display, etc. console.log('Collected Person Data:', peopleData); });
Key Adjustments for Your HTML
- Selector Matching: Since your code snippet was cut off, you’ll need to tweak the selectors (like
input[name="full-name"]or.datepicker) to exactly match the elements in your actual HTML. Double-check that each selector points to the correct input, datepicker field, image, and bio element inside each person’s<li>. - Pure Multidimensional Array: If you strictly need a nested array (instead of an array of objects), modify the
personInfoto be an array:const personInfo = [ $person.find('input[name="full-name"]').val(), $person.find('.datepicker').val(), $person.find('img.profile-pic').attr('src'), $person.find('.bio-text').val() ];
Testing with Your 2 Entries
Once you adjust the selectors to match your HTML, running this code after adding two people will log an array with two entries—each containing the data from their respective fields.
内容的提问来源于stack exchange,提问作者Jules Uadv Warner
相关产品推荐
相关产品推荐

