如何将jQuery函数调用结果存储到对象中以便后续访问?
The trick is to create a storage object outside your .each() loop—this way, it persists after the loop finishes and you can access its contents anytime afterward. Here's how to do it step by step:
Step 1: Initialize a storage object
First, declare an empty object (or array, if you prefer ordered access) before your .each() call. This will hold all the calculated values from each iteration.
Step 2: Store values inside the loop
Inside the .each() function, after calculating hours, minutes, and seconds, assign them to properties in your storage object. Use a unique key for each .time_tracker element—this could be the element's id (if it has one) or the loop index as a fallback.
Example Code
// Create an empty object to hold all tracker data const trackerData = {}; $('.time_tracker').each(function(index) { // Your existing logic to calculate hours, minutes, seconds let hours = ...; // Replace with your actual calculation let minutes = ...; let seconds = ...; // Use the element's ID as the key (if available) or a numbered identifier const uniqueKey = this.id || `tracker-${index}`; // Store the values in the object trackerData[uniqueKey] = { hours: hours, minutes: minutes, seconds: seconds }; });
Step 3: Access the stored data later
Once the loop completes, you can pull values from trackerData whenever you need them:
// Access data for a tracker with ID "work-timer" console.log(trackerData['work-timer'].hours); // Access data for the first tracker (index 0) console.log(trackerData['tracker-0'].seconds);
Alternative: Use an array for ordered access
If you don't need unique keys and just want to access data by the order of elements, an array works too:
const trackerDataArray = []; $('.time_tracker').each(function() { let hours = ...; let minutes = ...; let seconds = ...; trackerDataArray.push({ hours, minutes, seconds, element: this // Optional: store a reference to the DOM element }); }); // Access the second tracker's minutes console.log(trackerDataArray[1].minutes);
A quick note: Make sure your unique keys are actually unique (using the element's id is ideal here) to avoid overwriting data from different elements. You can also store additional info like the DOM element itself if you need to link back to it later.
内容的提问来源于stack exchange,提问作者Tintin81

