这适用于天气应用。我试图从json中获取一个值,将其赋值给一个变量,然后在json回调中的函数调用中使用该变量作为参数。如果我使用switch语句,这是有效的,但我试图避免这种情况,所以我构造了一个带有对象和html值的函数。运行时,它应该选择正确的html并将其附加到div。
问题是它只有在明确定义' icon'的值时才有效。在iconPicker函数中。否则,最后的警报会一直给我“未定义的”#。感觉我在这里错过了一些基本的范围问题。救命啊!
const iconPicker = (icon) => {
const rainy = '<div class="icon rainy"><div class="cloud"></div><div class="rain"></div></div>';
const sunny = '<div class="icon sunny"><div class="sun"><div class="rays"></div></div></div>';
const overcast = '<div class="icon cloudy"><div class="cloud"></div><div class="cloud"></div></div>';
const partlySunny = '<div class="cloud"></div><div class="sun"><div class="rays"></div></div>';
const stormy = '<div class="icon thunder-storm"><div class="cloud"></div><div class="lightning"><div class="bolt"></div><div class="bolt"></div></div></div>';
const snowy = '<div class="icon flurries"><div class="cloud"></div><div class="snow"><div class="flake"></div><div class="flake"></div></div></div>';
const iconObj = {
'rain': rainy,
'chancerain': rainy,
'clear': sunny,
'sunny': sunny,
'mostlysunny': sunny,
'fog': overcast,
'cloudly': overcast,
'hazy': partlySunny,
'mostlycloudy': partlySunny,
'partlycloudy': partlySunny,
'partlysunny': partlySunny,
'chancetstorms': stormy,
'tstorms': stormy,
'chanceflurries': snowy,
'chancesleet': snowy,
'chancesnow': snowy,
'flurries': snowy,
'sleet': snowy,
'snow': snowy
}
$('.icon').append(iconObj[icon]);
alert(iconObj[icon]);
}
const currentConditions = () => {
let icon;
$.getJSON('http://api.wunderground.com/api/e95fb12f6c69ae61/geolookup/conditions/q/autoip.json', function(json) {
console.log(json);
tempf = json.current_observation.temp_f;
tempc = json.current_observation.temp_c;
icon = json.current_observation.icon;
city = json.location.city;
country = json.location.country_name;
$('.location').html(city + ', ' + country);
$('.weather').html(tempf + '°' + '<a href=# class="scale scaleF">F</a>');
$('.weather').on('click', 'a', function(e) {
e.preventDefault();
let element = $(e.target);
if(element.hasClass('scaleF')) {
$('.weather').html(tempc + '°' + '<a href=# class="scale scaleC">C</a>');
} else if (element.hasClass('scaleC')){
$('.weather').html(tempf + '°' + '<a href=# class="scale scaleF">F</a>');
}
});
iconPicker(icon);
});
};