我为免费代码营做了天气应用程序,但我不知道为什么我的按钮不会将温度从摄氏温度变为华氏温度。 我认为这对于变量的恢复来说是一个问题,但我不知道在哪里。 我在代码中尝试了一些更改,但我只是绕圈子去了。
这是我的javascript:
$(document).ready(function(){
var long;
var lat;
var celsius;
var fahrenheit;
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;
lat = position.coords.latitude;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&lang=fr'+'&units=metric&appid=d475e2ed504ab40f4de6c1b3cba9ebcc';
$.getJSON(url, function(data){
var weatherType = data.weather[0].description;
var windSpeed = data.wind.speed;
var icon = data.weather[0].icon;
var city = data.name;
var country = data.sys.country;
var description = data.weather[0].description;
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
$('.card').html( city + '<br> Temp: '+Temp+' °C'+ '<br> Wind Speed:'+windSpeed+'M/s');
$('.icon').html('<img src="http://openweathermap.org/img/w/' + icon + '.png" /> ' + '<br>'+weatherType);
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
$('.btn').on('click', function() { change (); })
console.log(city);
console.log(weatherType);
console.log(windSpeed);
console.log(icon);
};
})
})
});
和HTML:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Weather App</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 weather' >
<div class="col-sm-6 text-center card">
</div>
<div class="col-sm-6 text-center text-uppercase icon">
</div>
<button type="button" class="btn degree">°C/°F</button>
</div>
</div>
</div>
<div class="text-center footer">by<a href="http://codepen.io/Th13um/"> Mathieu Dupré-Fontana</a>
</div>
<script src="js/app.js"></script>
有人可以帮帮我吗?
Ps:对不起,我的英语不好,我是法国人。
答案 0 :(得分:1)
celsius
设置为Temp
的值时,{p> celisus
似乎是一个数字,而不是字符串,Temp
设置为数字,而不是字符串
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
Temp
不等于"fahrenheit"
函数中的"celcius"
或change
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
}
.html()
也应该在change()
函数中调用,如果预期的结果是在元素的click
处切换到HTML的Celcius和Fahrenheit呈现。