我有这个代码块,它基于simpleweather.js:
$(document).ready(function() {
var conditionsImageClass;
$.simpleWeather({
location: 'Leon, Spain',
woeid: '',
unit: 'f',
success: function(weather) {
switch(weather.code) {
case 27:
conditionsImageClass = '.diw-clouds:before';
break;
case 28:
conditionsImageClass = '.diw-clouds-moon:before';
break;
default:
conditionsImageClass = '.test'
break;
}
alert(weather.code);
alert(conditionsImageClass);
var loc = '<h5>'+weather.city+', '+weather.region+'</h5>';
html = '<p>Today</p><p><strong>'+returnsDate()+'</strong></p>';
html += '<i class="' + conditionsImageClass + '"></i>';
html += '<h2><strong><i class="icon-'+weather.code+'"></i> '+weather.temp+'°'+weather.units.temp+'</strong></h2>';
html += '<h5 class="currently">'+weather.currently+'</h5>';
$("#location").html(loc);
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
});
现在,switch语句似乎没有执行。我没有完全充实它,因为我想在当前条件下测试它。目前,莱昂的条件代码为“28”或多云。但即使存在“28”的情况,switch语句也会默认为默认值。任何想法为什么这样做?如果您需要更多代码,请告诉我们。
答案 0 :(得分:1)
您不能同时使用位置:'Leon,西班牙', + woeid:'',。 为了识别位置,您可以在案例位置使用有效字段。
$.simpleWeather({
location: 'Leon, Spain',
unit: 'f',
success: function(weather) {
console.log('weather.code is: ' + weather.code);
switch(weather.code) {
case '27':
conditionsImageClass = '.diw-clouds:before';
break;
case '28':
conditionsImageClass = '.diw-clouds-moon:before';
break;
default:
conditionsImageClass = '.test'
break;
}
console.log('conditionsImageClass is: ' + conditionsImageClass);
},
error: function(error) {
console.log('Error: ' + error);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
答案 1 :(得分:-1)
weather.code
可能是一个字符串。您的案例正在检查整数,因此它们不匹配。您需要使用parseInt()
解析天气代码,或将每个案例转换为字符串。
switch(parseInt(weather.code)) {
case 27:
conditionsImageClass = '.diw-clouds:before';
break;
case 28:
conditionsImageClass = '.diw-clouds-moon:before';
break;
default:
conditionsImageClass = '.test';
}
显示差异的简化示例
console.log(displayWeatherCode(27)); // "27!"
console.log(displayWeatherCode("27")); // "Default!"
function displayWeatherCode(weatherCode) {
switch(weatherCode) {
case 27:
return "27!";
case 28:
return "28!";
default:
return "Default!";
}
}
&#13;