如何解决将“对象”的“ clearsky”属性值分配给天气,以便通过图像标签中的src
预期结果是首先从对象“对象”的数组中找到天气字符串,然后将“天气”变量的值设置为等于clearsky值(即链接)的值。
let weather = "clearsky";
const objects = [
{ "clearsky": "http://openweathermap.org/img/wn/11d@2x.png" },{ "cloudy": "http://openweathermap.org/img/wn/19d@2x.png" },{ "rainny": "http://openweathermap.org/img/wn/10d@2x.png" },{ "sunny": "http://openweathermap.org/img/wn/12d@2x.png" },];
//expected result is to first find weather string from array of object "objects" and then set value of weather equal to value of
weather = {
/* <img src={weather} alt=""/> */
};
解决方法
我假设您想编写某种函数来显示与对象数组中的正确值(天气类型)相对应的图像。
我添加了这些<img>
标签(用于在您的html中显示)。
<img id="img-clearsky">
<img id="img-rainy">
我稍微更改了对象数组的结构,以便可以通过简单的方式访问属性值。我做了一个遍历数组的函数,如果找到与对象type
相匹配的函数,它将使用相应的imgurl
以给定的{{1}作为元素的src
加载}。
id
,
执行此操作的方法有多种,但是我会用一个函数包装此逻辑-特别是如果您打算将其拆分为几个常量。
const WeatherTypeImage = (weatherType = 'clearsky') =>
Object.assign(document.createElement('img'),{
src: {
"clearsky": "http://openweathermap.org/img/wn/11d@2x.png","cloudy": "http://openweathermap.org/img/wn/19d@2x.png","rainny": "http://openweathermap.org/img/wn/10d@2x.png","sunny": "http://openweathermap.org/img/wn/12d@2x.png",}[weatherType],alt: '',})
document.querySelector('.js-container').appendChild(
WeatherTypeImage()
)
<div class="js-container"></div>
或者,如果您希望拥有HTML字符串模板:
const WeatherTypeImage = (weatherType = 'clearsky') => {
const src = {
"clearsky": "http://openweathermap.org/img/wn/11d@2x.png",}[weatherType]
return Object.assign(document.createElement('template'),{
innerHTML: `<img src="${src}" alt="">`
}).content
}
document.querySelector('.js-container').appendChild(
WeatherTypeImage()
)
<div class="js-container"></div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。