我正在使用weatherapi 编写一个天气应用程序。 我可以检索一般天气,但我收到图标的 net::ERR_FILE_NOT_FOUND 消息,但是图标 url 显示在 HTML 中,并且当我在新选项卡中打开它时它正在工作。 我还收到了未定义的临时查询和类似的查询。
如有任何帮助,我们将不胜感激。
我的 JavaScript 代码如下:
const
search = document.getElementById("keyword"),
submitBtn = document.getElementById("submit-button"),
cityName = document.getElementById("city"),
showDate = document.getElementById("date"),
showTime = document.getElementById("time"),
showWeather = document.querySelector("#weather h1"),
weatherPic = document.querySelector("#weather div"),
temperature = document.querySelector("#temperature"),
feelsLike = document.querySelector("#feels-like");
async function getWeather(e) {
const keyword = document.querySelector("#keyword").value;
e.preventDefault();
console.log(keyword);
const response = await fetch(`http://api.weatherapi.com/v1/current.json?key=179428b368194d318d421509232011&q=${keyword}`, {mode: 'cors'});
const weatherData = await response.json();
console.log(weatherData);
const city = keyword.charAt(0).toUpperCase() + keyword.slice(1);
cityName.innerText = city;
showWeather.innerText = weatherData.current.condition.text;
const weatherImg = document.createElement("img");
weatherImg.setAttribute("id", "weather-img");
weatherImg.src = weatherData.current.condition.icon;
const showTemp = document.createElement("span");
const showFeelsLike = document.createElement("span");
showTemp.innerText = weatherData.current.condition.temp_c;
showFeelsLike.innerText = weatherData.current.condition.feelslike_c;
weatherPic.appendChild(weatherImg);
temperature.appendChild(showTemp);
feelsLike.appendChild(showFeelsLike);
};
submitBtn.addEventListener("click", getWeather);
<div id="wrapper">
<header>
<div id="logo"><img src="images/myweatherapp.png" alt="My Weather App">
<h2>My Weather App</h2></div>
<div id="search">
<form>
<input type="text" id="keyword" name="search-term" placeholder="City name">
<input type="submit" id="submit-button" value=">>">
</form>
</div>
</header>
<section id="content">
<div id="content-header">
<h1>The weather in <span id="city">{Search for your city}</span> today!</h1>
<div id="weather">
<div></div>
<h1></h1>
</div>
</div>
<p id="date"></p><p id="time"></p>
<div id="weather-report">
<div id="temperature"></div>
<div id="feels-like"></div>
</div>
</section>
</div>
编辑:由于某种原因,当我将其粘贴到此代码片段中时,图标显示了,但它没有显示在浏览器上。其他项目仍然显示为未定义!
尝试:weatherImg.src =“https:”+weatherData.current.condition.icon; 由于某种原因,默认值为 file://,而您正在寻找 https://
致以诚挚的问候。