JavaScript动态添加Div顺序问题求助:FreeCodeCamp Twitch TV API项目
Hey there! I totally get your frustration—nothing's more annoying than having your layout shift randomly every time you refresh. Let's break down why this is happening and how to fix it.
Why the Order Changes
The problem almost certainly comes from how you're handling the API requests. When you fetch data for each Twitch streamer, those are asynchronous calls—meaning the browser doesn't wait for one to finish before starting the next. So the responses can come back in any order, depending on how fast each request is processed by Twitch's servers. If you're appending each div as soon as you get a response, that's why the order changes every time.
Step-by-Step Solution
We need to first collect all the data, then render everything in the fixed order you want (based on your original list of streamer names). Here's how to do it:
Define your fixed streamer list
This will be our source of truth for the display order:const streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp"]; // Add your full list hereCreate fetch promises for each streamer
We'll attach the streamer's username to the fetched data so we can match it later:const fetchPromises = streamers.map(streamer => fetch(`https://api.twitch.tv/kraken/streams/${streamer}`) .then(response => response.json()) .then(data => ({ ...data, username: streamer })) // Link data to the streamer name );Wait for all requests to complete, then sort and render
UsePromise.allto wait for every API call to finish, then sort the results to match your original list before creating divs:Promise.all(fetchPromises) .then(allData => { // Sort fetched data to match our original streamer order const sortedData = streamers.map(streamer => allData.find(entry => entry.username === streamer) ); // Render each div in the sorted order sortedData.forEach(entry => { const streamDiv = document.createElement('div'); // Add your custom content here (name, status, logo, etc.) streamDiv.innerHTML = ` <h4>${entry.username}</h4> <p>${entry.stream ? "Live now!" : "Offline"}</p> `; // Append to your container element document.getElementById('stream-container').appendChild(streamDiv); }); }) .catch(err => console.error('Error fetching stream data:', err));
Key Takeaway
By collecting all data first and then sorting it against your original streamer list, you guarantee that the divs will always render in the order you want—no matter the order the API responses come in.
If you were previously appending divs inside each fetch's .then() block, replacing that with this method should resolve the order issue right away. Feel free to adjust the code to fit your existing project structure!
内容的提问来源于stack exchange,提问作者iffitheking

