【发布时间】:2020-06-24 22:25:50
【问题描述】:
所以,我正在尝试从 openweatherAPI 添加一个 img 元素,当用户通过输入城市获取当前网络统计信息时,该元素会显示一个与 JSON 结果中发现的内容相关的图标(即散乱云的图像,晴朗的天空等)。为了显示 img,我知道我需要将 url 粘贴到 img 标签的“src”部分。 URL 看起来像:
const png = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
然而,为了使这种动态化,img 标签“src”必须根据输入的城市图像文件的内容而改变。
我有从 js 文件中的“icon”和“png”变量定义的逻辑。我的问题是,如何根据用户在页面上输入的城市让 html img 'src' 填充我的“png”变量的结果?
我在下面包含了 html 和 javasript 代码
const button = document.querySelector(".button")
const inputValue = document.querySelector(".inputValue")
const name = document.querySelector(".name")
const desc = document.querySelector(".desc")
const temp = document.querySelector(".temp")
const img = document.querySelector(".image")
button.addEventListener('click', function (){
fetch('http://api.openweathermap.org/data/2.5/weather?q='+ inputValue.value +'&units=imperial&appid=61dcc0033e94c4172d2bb94bb607fc5d')
.then(response => response.json())
.then(data => {
const nameValue = data['name']
const tempValue = data['main']['temp']
const descValue = data['weather'][0]['description']
const icon = weatherData.weather[0].icon
const png = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
name.innerHTML = nameValue
temp.innerHTML = tempValue
desc.innerHTML = descValue
img.innerHTML =
})
.catch(err => alert("Wrong City name!"))
})
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>OpenWeatherAPI</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="desc"></p>
<p class="temp"></p>
<img class="image" src="">
</div>
<script src='main.js'></script>
</body>
</html>
【问题讨论】:
-
img.src = png;(假设png变量是图片的来源)
标签: javascript html json api openweathermap