Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环提取请求在最后一项之前返回一个错误_Javascript - Fatal编程技术网

Javascript 循环提取请求在最后一项之前返回一个错误

Javascript 循环提取请求在最后一项之前返回一个错误,javascript,Javascript,我有一个循环,它遍历一个位置数组并检索数组中各个位置的当前天气。但由于某些原因,我得到了TypeError:在最后一个请求工作之前,无法将属性“innerHTML”设置为null 而之前所有的都工作正常。我真的不知道为什么这里会出错 const getData = () => { for (const country in weatherCountries) { console.log(country); fetch(`${baseUrl}?lat=${wea

我有一个循环,它遍历一个位置数组并检索数组中各个位置的当前天气。但由于某些原因,我得到了TypeError:在最后一个请求工作之前,无法将属性“innerHTML”设置为null

而之前所有的都工作正常。我真的不知道为什么这里会出错

const getData = () => {
   for (const country in weatherCountries) {
      console.log(country);
      fetch(`${baseUrl}?lat=${weatherCountries[country].lat}&lon=${weatherCountries[country].long}&APPID=${appId}`)
         .then(res => res.json())
         .then(data => {
            conditions = data.weather[0].main;
            temperature = data.main.temp - 273.15;
            temperature = Math.round(temperature);
            document.getElementById(weatherCountries[country].name).innerHTML = `<h5>Current Weather</h5>
               <table>
                  <tr><th>Conditions:</th><th>Temperature:</th></tr>
                  <tr><td>${conditions}</td><td>${temperature}</td></tr>
               </table>`;
         })
   }
}

使用if条件检查对元素进行换行,以便如果该国家/地区不在页面中,它不会崩溃,并继续检查下一个国家/地区:

let countryElement = document.getElementById(weatherCountries[country].name);
if (countryElement) {
    countryElement.innerHTML = `<h5>Current Weather</h5>
    ...
} else {
    console.log('The country: ' + country + ' is not found');
}

和控制台记录国家/地区,以便您可以在浏览器的控制台中检查您在哪些国家/地区发生错误以防止其发生。

其中一个元素不存在weatherCountries[country]。在DOM中,我建议您确认最后一个元素之前的元素具有正确的国家/地区id weatherCountries[国家]。名称

或者,您可以通过以下方式避免错误:

.then(data => {
            conditions = data.weather[0].main;
            temperature = data.main.temp - 273.15;
            temperature = Math.round(temperature);
            element = document.getElementById(weatherCountries[country].name);
            if(element) {
             element.innerHTML = `<h5>Current Weather</h5>
               <table>
                  <tr><th>Conditions:</th><th>Temperature:</th></tr>
                  <tr><td>${conditions}</td><td>${temperature}</td></tr>
               </table>`;
             }
         })

document.getElementByIdweatherCountries[country]。名称返回null。。。因此,在您的页面上找不到作为元素id的国家名称。当然,这可以防止错误发生,但无法解决问题…当然,这可以防止错误发生,但无法解决问题。。。