为了账号安全,请及时绑定邮箱和手机立即绑定

在我重新加载页面之前,JavaScript 不会从输入字段中获取国家/地区

在我重新加载页面之前,JavaScript 不会从输入字段中获取国家/地区

胡子哥哥 2023-03-24 13:35:57
我正在尝试使用 disease.sh API 制作一个冠状病毒病例跟踪器,但 JavaScript 无法从输入字段中获取国家/地区,除非刷新页面。我尝试删除事件侦听器并添加一个 onclick 属性,但那没有不工作,所以我猜这与未正确制作端点有关。HTML:<!DOCTYPE html><html><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>
查看完整描述

2 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

试试这个方法


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>


<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>


查看完整回答
反对 回复 2023-03-24
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

我已经修改了您的 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>';

  } 

};



查看完整回答
反对 回复 2023-03-24
  • 2 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信