Мои данные трехчасового прогноза не отражаются на моем HD, они показали все возможные прогнозыHtml

Программисты Html
Ответить
Anonymous
 Мои данные трехчасового прогноза не отражаются на моем HD, они показали все возможные прогнозы

Сообщение Anonymous »

`Я работаю над своим первым проектом на JavaScript и создаю приложение о погоде.
Мне удалось извлечь данные трехчасового прогноза, но они показывают только первые данные. Например, в моем html только данные за 21:00, а остальное не отражается. Он должен был отображать все возможные данные прогноза.
При написании HTML-кода я написал 6 элементов, которые отвечают за хранение данных прогноза, но на самом деле мне нужно было 8. Поэтому я создал элемент прогноза как способ создания оставшегося HTML-кода. Я хочу добавить его с помощью элемента прогноза контейнера.innerHTML +=. Я этого еще не сделал, потому что только 1 из 6 у меня уже показывал данные прогноза. Я хочу, чтобы данные трехчасового прогноза автоматически отображались в HTML каждые 24 часа

Код: Выделить всё

async function getForecast() {
try {

// const citySearch = document.getElementById('search-city').value;
const apiKey = 'APIKEY';
const forecastFullUrl = `https://api.openweathermap.org/data/2.5/forecast?q=Dudley&appid=${apiKey}&units=metric`;

console.log('fetching forecast URL:', forecastFullUrl)

const forecastData = {
example forecast data
}
console.log(forecastData);

displayCurrentForecastData(forecastData.list);
} catch (error) {
console.error('error fetching hourly forecast data:', error);
alert('Failed to fetch hourly forecast data');
}
}
getForecast();

function displayCurrentForecastData(forecastList) {

// compare today date with the date in the dorecast data and return only the ones that matches today's date

const currentDate = new Date();
const currentDateStringToShowOnMainPage = currentDate.toISOString().split('T')[0];
// to make the date on the main page be the current date
document.getElementById('current-date').textContent = currentDateStringToShowOnMainPage;

//  to only shown current day's weather forecast
const currentDayForecast = forecastList.filter((forecast) => {

const time = new Date(forecast.dt * 1000)
const forecastDateString = time.toISOString().split('T')[0];
return forecastDateString === currentDateStringToShowOnMainPage;
})

// this to make  more html children since i only created 6 spaces in th e html for the 3 hours weather details
const forecastContainer = document.getElementById('selected-hour-details')
// forecastContainer.innerHTML = '';

currentDayForecast.forEach((forecast, index) =>  {

const forecastItem = document.createElement('div');
forecastItem.className = 'selected-hour-details';
const time = new Date(forecast.dt * 1000)
const timeString = time.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit"
});

const temp = forecast.main.temp;
const description = forecast.weather[0].description;
const icon = `http://openweathermap.org/img/wn/${forecast.weather[0].icon}`;

// to update the 3 hourly html with the forecast details

document.querySelector('.forecasttime').textContent = timeString;
document.querySelector('.forecasttemp').textContent = `${temp}°C: ${description}`;
document.querySelector('.weather-icon').src = icon;

// /create more spaces

forecastItem.innerHTML = `
${timeString}
[img]${icon}[/img]
${temp}°C: ${description}
`
forecastContainer.innerHTML += forecastItem;
})
}

Код: Выделить всё



00:00

4°

01:00

5•

02:00

5•

03:00

5•

04:00

5•

05:00

5•




Подробнее здесь: https://stackoverflow.com/questions/794 ... e-able-for
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»