@Meynr

Почему не выводит правильно информацию о погоде?

Помогите пожалуйста исправить ошибку. API работает. Пример правильной работы на фото.
5fd60c156f775673294851.png

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>
<body>
<header>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                </ul>
                <form class="form-inline my-2 my-lg-0">
                    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-warning my-2 my-sm-0" type="submit">Search</button>
                </form>
            </div>
        </nav>
    </div>

</header>

<section id="main" class="mt-3">
    <div class="container">
        <div class="row">
            <div class="col-6 col-md-4 col-lg-3">
                <div class="list-group" id="cities" >
                </div>
            </div>
            <div class="col-6 col-md-8 col-lg-9">
                <div class="card">
                    <div class="card-body">
                        <h3 class="card-title" id="idcities"></h3>
                        <img src="http://openweathermap.org/img/wn/10d@2x.png" alt="" id="icon">
                        <table class="table table-striped" >
                            <tr>
                                <th>Pressure</th>
                                <td id="pres"></td>
                            </tr>
                            <tr>
                                <th>Humidity</th>
                                <td id="hum"></td>
                            </tr>
                            <tr>
                                <th>Temperature</th>
                                <td id="temp"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>
<script src="task.js"></script>

</body>
</html>

async function sendRequesr(city) {
    const apiKey = "6f84df52527ba5a49665558cd819a86d"
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
    const result = await response.json();
    return result;
}
 
async function sendCity() {
    const url = "https://raw.githubusercontent.com/alexanderkuzmenko/weatherapplication/master/cities.json"
    const response = await fetch(url);
    const result = await response.json();
    return result;
}
 
sendCity().then((response) => {
 
    let arr = [];
    let mass = [];
    let cities = document.getElementById('cities')
    for (let i = 0; i < response.length; i++) {
        arr[i] = response[i].city
        let a = document.createElement('a')
        a.innerHTML = `${arr[i]}`
        a.classList = "list-group-item list-group-item-action"
        a.href = "#"
        mass.push(a)
        cities.appendChild(a)
    }
   for (let i = 0; i < arr.length; i++) {
        let elementById = document.getElementById('idcities')
        mass[i].addEventListener('click', function (){
            for(let i = 0; i < arr.length; i++){
                mass[i].classList.remove('active')
            }
            mass[i].classList.add("active")
            sendRequesr(mass[i]).then((response) =>{
                elementById.innerHTML = `Weather in ${arr[i]}`
                pres.innerHTML = `${response.main.pressure}`
                hum.innerHTML = `${response.main.humidity}`
                temp.innerHTML = `${Math.round(response.main.temp - 273, 0)}`
                icon.src = `http://openweathermap.org/img/w/${response.weather[0].icon}.png`
            }).catch((error) => {
                elementById.innerHTML = "error"
                pres.innerHTML = "error"
                hum.innerHTML = "error"
                temp.innerHTML = "error"
                icon.src = "error"
                console.log(error)
            });
        })
    }
}).catch((error) => {
    console.log(error)
 
});
  • Вопрос задан
  • 132 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
Потому что передаёте в sendRequesr вместо строки с городом соответствующий ей элемент <a>.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
28 нояб. 2024, в 05:21
2000 руб./за проект
28 нояб. 2024, в 05:18
500 руб./за проект
28 нояб. 2024, в 03:51
3500 руб./за проект