简体   繁体   中英

How do I display the correct day of the week for each of the 5 days in a weather forecast app using JS?

So I'm having a bit of trouble. I've managed to pull only the day of the week from the date data retrieved from the openweathermap API, but I'm having trouble getting it to correctly display the day of the week for each of the 5 days I'm trying to include in the forecast. It's just assigning the same weekday name to each day of the forecast. Anyone able to help?

fetch(forecast)
    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
        
        data.list.forEach(list => {
            
            const iconId = list.weather[0].id;

            
            const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            const d = new Date(data.list[0].dt * 1000);
            const dayName = days[d.getDay()];
            console.log(dayName)

            // Generate and append html elements on the page
            const container = document.querySelector('.container');
            
            const forecastCard = document.createElement('div');
            container.appendChild(forecastCard)
            forecastCard.classList.add('forecast-card')

            const date = document.createElement('h2');
            date.textContent = dayName;
            forecastCard.appendChild(date);
            date.classList.add('date');

            const currentTemp = document.createElement('p');
            currentTemp.textContent = list.main.temp;
            forecastCard.appendChild(currentTemp);
            currentTemp.classList.add('current-temp');
            
            const icon = document.createElement('img');
            icon.src = `./icons/${list.weather[0].icon}.png`;
            forecastCard.appendChild(icon);
            icon.classList.add('icon');
            
            const conditions = document.createElement('p');
            conditions.textContent = list.weather[0].description;
            forecastCard.appendChild(conditions);
            conditions.classList.add('conditions');
            
            const humidity = document.createElement('p');
            humidity.textContent = `Humidity: ${list.main.humidity}%`;
            forecastCard.appendChild(humidity);
            humidity.classList.add('humidity');
            
    })
                    
    });

I don't think you need to define a datalist inside date:

let d = new Date();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let weekDay = days[d.getDay()];
console.log(weekDay);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM