JavaScript не получает страну из поля ввода, пока я не перезагружу страницу

#javascript #html #css

#javascript #HTML #css

Вопрос:

Я пытаюсь создать систему отслеживания случаев заражения коронавирусом, используя disease.sh API, но JavaScript не получает страну из поля ввода, если не обновить страницу.Я попытался удалить прослушиватель событий и добавить атрибут onclick, но это не сработало, поэтому я предполагаю, что это как-то связано с неправильным созданием конечной точки.

HTML:

 <!DOCTYPE html>
<html lang="en">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="style.css" type="text/css">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>
    <nav class="navbar navbar-expand-md bg-dark navbar-dark">
        <!-- Brand -->
        <a class="navbar-brand" href="#">
            <img src="./images/logo.png" class="img-fluid" alt="logo">
        </a>

        <p class="display-none">Corona Virus Case Tracker</p>

        <!-- Toggler/collapsibe Button -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Navbar links -->
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item" onmouseover="changeThing()" onmouseout="changeThingBack()">
                    <a class="nav-link active" id="list-item1" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">More information</a>
                </li>
            </ul>
        </div>
    </nav>

 

    <input type="text" id="submit-country">
    <input type="submit" id="submit-button" value="get cases" />

    <div class="case-results">

    </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="main.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM"
        crossorigin="anonymous"></script>
</body>

</html>
  

CSS:

 .navigation-bar-logo {
    width: 240px;
}

img {
  width: 140px;
}

li {
    margin: 20px;
    font-size: 15px;
}

.case-results {
  color: blue;
}

a {
  color: white;
  text-decoration: none;
  text-transform: uppercase;
  font-family: Arial;
  display: inline-block;
  padding: 16px 32px;
  background-image: linear-gradient(120deg, transparent 50%, white 50%);
  background-size: 250%;
  transition: all 0.4s;
  letter-spacing: 2px;
}

p.display-none {
  font-size: 16px;
  color: white;
  margin: 0;
  padding: 0;
}

li:hover a {
  background-position: 100%;
  color: #313131 !important;
  transform: translateX(16px);
}

@media only screen and (max-width: 600px) {
    p.display-none {
      display: none;
    }
    li[class="nav-item"] {
      text-align: center;
    }
  }
  

JavaScript:

 let case_results = document.querySelector(".case-results");
let inputField = document.getElementById('submit-country');
let countrySubmitted = inputField.value;
const submit = document.getElementById("submit-button");
const URL = 'https://disease.sh/v3/covid-19/countries/';
const lastParams = '?strict=true';
const endpoint = `${URL}${countrySubmitted}${lastParams}`;


/*

Test to change text on hover, to be replaced with icons

function changeThing() {
  document.getElementById('list-item1').innerHTML = 'hduashdas';
}

function changeThingBack() {
  document.getElementById('list-item1').innerHTML = 'Home';
}


*/

//const requestURL = `https://disease.sh/v3/covid-19/countries/Moldova?strict=true`;

//Makes a call to the API and retrieves information about a specific country
const getCases = async () => {
  try {
    const response = await fetch(endpoint, { cache: "no-cache" });
    if (response.ok) {
      const jsonResponse = await response.json();
      renderResponse(jsonResponse);
    }
  } catch (error) {
    console.log(error);
  }
};

//Clears the previous results in the div and displays new ones
function displayCases(event) {
  while(case_results.firstChild) {
    case_results.removeChild(case_results.firstChild)
  }
  getCases();
}

submit.addEventListener('click', displayCases);

const renderResponse = (res) => {
  if (res != null) {
    console.log(res.updated);
    case_results.innerHTML = `cases in ${countrySubmitted} : ${res.cases}`   '<br>';
  } 
};
  

Комментарии:

1. Это потому, что вы считываете значение из своего ввода перед нажатием кнопки отправки. Переместите countrySubmitted = inputField.value; и endPoint внутренний the displayCases обратный вызов

Ответ №1:

Попробуйте этот способ

 let case_results = document.querySelector(".case-results");
let inputField = document.getElementById('submit-country');
const submit = document.getElementById("submit-button");


/*

Test to change text on hover, to be replaced with icons

function changeThing() {
  document.getElementById('list-item1').innerHTML = 'hduashdas';
}

function changeThingBack() {
  document.getElementById('list-item1').innerHTML = 'Home';
}


*/

//const requestURL = `https://disease.sh/v3/covid-19/countries/Moldova?strict=true`;

//Makes a call to the API and retrieves information about a specific country
const getCases = async () => {
let countrySubmitted = inputField.value;
const URL = 'https://disease.sh/v3/covid-19/countries/';
const lastParams = '?strict=true';
const endpoint = `${URL}${countrySubmitted}${lastParams}`;

  try {
    const response = await fetch(endpoint, { cache: "no-cache" });
    if (response.ok) {
      const jsonResponse = await response.json();
      renderResponse(jsonResponse);
    }
  } catch (error) {
    console.log(error);
  }
};

//Clears the previous results in the div and displays new ones
function displayCases(event) {
  while(case_results.firstChild) {
    case_results.removeChild(case_results.firstChild)
  }
  getCases();
}

submit.addEventListener('click', displayCases);

const renderResponse = (res) => {
if (res != null) {
    case_results.innerHTML = `cases in ${res.country} : ${res.cases}`   '<br>';
  } 
};  
 .navigation-bar-logo {
    width: 240px;
}

img {
  width: 140px;
}

li {
    margin: 20px;
    font-size: 15px;
}

.case-results {
  color: blue;
}

a {
  color: white;
  text-decoration: none;
  text-transform: uppercase;
  font-family: Arial;
  display: inline-block;
  padding: 16px 32px;
  background-image: linear-gradient(120deg, transparent 50%, white 50%);
  background-size: 250%;
  transition: all 0.4s;
  letter-spacing: 2px;
}

p.display-none {
  font-size: 16px;
  color: white;
  margin: 0;
  padding: 0;
}

li:hover a {
  background-position: 100%;
  color: #313131 !important;
  transform: translateX(16px);
}

@media only screen and (max-width: 600px) {
    p.display-none {
      display: none;
    }
    li[class="nav-item"] {
      text-align: center;
    }
  }  
 <!DOCTYPE html>
<html lang="en">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="style.css" type="text/css">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>
    <nav class="navbar navbar-expand-md bg-dark navbar-dark">
        <!-- Brand -->
        <a class="navbar-brand" href="#">
            <img src="./images/logo.png" class="img-fluid" alt="logo">
        </a>

        <p class="display-none">Corona Virus Case Tracker</p>

        <!-- Toggler/collapsibe Button -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Navbar links -->
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item" onmouseover="changeThing()" onmouseout="changeThingBack()">
                    <a class="nav-link active" id="list-item1" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">More information</a>
                </li>
            </ul>
        </div>
    </nav>

 

    <input type="text" id="submit-country">
    <input type="submit" id="submit-button" value="get cases" />

    <div class="case-results">

    </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="main.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM"
        crossorigin="anonymous"></script>
</body>

</html>  

Ответ №2:

Я изменил ваш javascript и подтвердил, что он работает.

 let case_results = document.querySelector(".case-results");
let inputField = document.getElementById('submit-country');
let countrySubmitted = inputField.value;
const submit = document.getElementById("submit-button");
const URL = 'https://disease.sh/v3/covid-19/countries/';
const lastParams = '?strict=true';
var endpoint = `${URL}${countrySubmitted}${lastParams}`;


/*

Test to change text on hover, to be replaced with icons

function changeThing() {
  document.getElementById('list-item1').innerHTML = 'hduashdas';
}

function changeThingBack() {
  document.getElementById('list-item1').innerHTML = 'Home';
}


*/

//const requestURL = `https://disease.sh/v3/covid-19/countries/Moldova?strict=true`;

//Makes a call to the API and retrieves information about a specific country
const getCases = async () => {
  try {
    const response = await fetch(endpoint, { cache: "no-cache" });
    if (response.ok) {
      const jsonResponse = await response.json();
      renderResponse(jsonResponse);
    }
  } catch (error) {
    console.log(error);
  }
};

//Clears the previous results in the div and displays new ones
function displayCases(event) {
  countrySubmitted = inputField.value;
  endpoint = `${URL}${countrySubmitted}${lastParams}`;
  while(case_results.firstChild) {
    case_results.removeChild(case_results.firstChild)
  }
  getCases();
}

submit.addEventListener('click', displayCases);

const renderResponse = (res) => {
  if (res != null) {
    console.log(res.updated);
    case_results.innerHTML = `cases in ${countrySubmitted} : ${res.cases}`   '<br>';
  } 
};
  

Комментарии:

1. Спасибо за помощь, оба решения работают